A really small tutorial introducing the 'for' loop, good for C++ newbies and programming beginners.
In this tutorial I expect you to have a little knowledge about programming, but to understand at least the C++ variables and other basic information.
Like in any other programming language, loops are very useful for repeating tasks. For is probably the best example of a loop.
In this example we will see how to output a string ten times. We make use of â€˜coutâ€™ only once.
// Demonstrating the for loop
using namespace std;
int counter; // This variable will be changed by the loop
for (counter = 0; counter < 10; counter++) // Initialize to 0, check the current value and increment it
cout << "Loop number " << counter << "\n"; // Output some text and the value the variable holds
Letâ€™s dissect the code a little:
int counter – create a variable that will hold a different value each loop.
for (counter = 0 – initialize the variable to the value 0.
counter < 10 – check if the variable holds a value smaller than 10. If it does, the loop continues.
counter++ – increment the variable by one. As you may know, itâ€™s equal to counter = counter + 1, but shorter.
The variable continues to be incremented, until it reaches 10. When the variable holds 10, the â€˜counter < 10â€™ expression returns false, and the loop stops.
Check the following example:
// More about the for loop
using namespace std;
cout << "Please input the starting number: ";
cin >> start_num;
cout << "Please input the ending number: ";
cin >> end_num;
for (counter = start_num; counter <= end_num; counter++)
cout << counter << "\n";
for (counter = start_num – initialize the variable to the value of start_num.
counter <= end_num – check if the variable holds a value smaller or equal than the end_num variable. If it does, the loop continues.
counter++ – increment the variable by one.
This time the loop checks if the variable is smaller or equal, not just smaller.
If start_num was 3 and end_num was 9, and we used a counter < end_num condition, the result would be this:
Because when counter hits the value 9, the condition returns false. 9 is not smaller than 9, it is equal.
This is the result because when the counter hits the value 9, the condition returns false. 9 is not smaller than 9, it is equal.