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 (;):

  1. Iterator variable, to which we assign a value in the first part.
  2. Condition, which as long as it's true, the loop will repeat.
  3. 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
2

The notation counter++ is a shortened version of counter = counter + 1. This just increases the value of counter by 1.

Step by step it executes:

  1. We create iterator variable counter of type int with value 0.
  2. The condition is counter < 3, which means the loop will repeat as long as counter is less than 3.
  3. counter++ increases the value of counter by 1 at the end of each repetition. In the first iteration it will have value 0. In the second iteration value 1 etc.
  4. The code in curly braces, std::cout << counter << std::endl;, runs in each iteration until the condition becomes false. The condition will be false when counter is greater than or equal to 3.

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

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/9

For Loop | Start Coder