For Loop
Another type of loop in C++ is the for loop, which allows us to repeatedly execute a block of code similar to the while loop. The for loop is often used when we know how many times we want to perform some operation, or when we want to go through all elements in a sequence. Whereas the while loop is used in the opposite case, when we don't know how many times we need to repeat the loop.
The for loop contains three parts, which are separated by semicolons (;):
- Iterator variable, to which we assign a value in the first part.
- Condition, which as long as it's true, the loop will repeat.
- Change of the iterator variable value.
The structure of the for loop looks as follows:
for (int counter = 0; counter < 3; counter++) {
std::cout << counter << std::endl;
}This prints:
0
1
2The notation counter++ is a shortened version of counter = counter + 1. This just increases the value of counter by 1.
Step by step it executes:
- We create iterator variable
counterof typeintwith value0. - The condition is
counter < 3, which means the loop will repeat as long ascounteris less than 3. counter++increases the value ofcounterby 1 at the end of each repetition. In the first iteration it will have value 0. In the second iteration value 1 etc.- The code in curly braces,
std::cout << counter << std::endl;, runs in each iteration until the condition becomesfalse. The condition will befalsewhencounteris greater than or equal to3.
In C++, shorthand notation for decrementation (counter--) is also often used.
Instructions
Using a for loop, print numbers from 15 to 20 inclusive.
Start programming for free
3/9