Introduction:
In the world of C++ programming, mastering different types of loops is crucial. Today, we’ll embark on a journey to explore the versatile “while” loop by creating a simple program to print tables. Whether you’re a coding beginner or looking to expand your C++ skills, this article will guide you through the process step by step.
Understanding While Loops:
While loops are a fundamental part of programming, allowing us to execute a block of code repeatedly as long as a specified condition holds true. They offer flexibility and are particularly useful when the number of iterations isn’t known in advance.
The C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> using namespace std; // Function to print a table using a while loop void printTable(int number) { int i = 1; // While loop to print the table while (i <= 10) { cout << number << " * " << i << " = " << number * i << endl; i++; } } int main() { int inputNumber; // Get the number for the table from the user cout << "Enter a number to print its table: "; cin >> inputNumber; // Print the table using the printTable function printTable(inputNumber); return 0; } |
Breaking Down the Code:
- The
printTable
function uses a “while” loop to print the multiplication table of a given number (number
) up to 10. - The loop continues as long as the condition
i <= 10
is true, printing each line of the table and incrementingi
in each iteration. - In the
main
function, the user inputs a number, and the program prints the multiplication table using theprintTable
function.
Conclusion:
Congratulations! You’ve now created a C++ program that prints tables using a “while” loop. While loops are an essential tool in programming, and this simple example demonstrates their utility in repetitive tasks. Feel free to experiment with different numbers and explore the power of while loops in your C++ journey.