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
#include <iostream>
using namespace std;
int main()
{
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
}
return 0;
}
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
#include <iostream>
using namespace std;
int main()
{
cout << "Please input the starting number: ";
int start_num;
cin >> start_num;
cout << "Please input the ending number: ";
int end_num;
cin >> end_num;
int counter;
for (counter = start_num; counter <= end_num; counter++)
{
cout << counter << "\n";
}
return 0;
}
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:
1
2
3
4
5
6
7
8
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.