Namespaces
Variants
Actions

The for loop

From cppreference.com


The for loop is designed to repeat a set of statements a certain number of times, though it is flexible enough to handle many other looping tasks.

It looks like this:

for (/*init*/ ; /*while-condition*/ ; /*increment*/) {
    // statements
}

Both the init and increment expressions can be empty. The braces are optional if there is only a single statement.

It works like this:

1) Run the expression /*init*/.
2) Run the expression /*while-condition*/, which should return true or false.
a) If the result is true, run the statements in the block.
b) If the result is false, skip over the block without running the statements (and move on to whatever code follows the for statement).
3) Run the expression /*increment*/.
4) Go to step 2.

For example:

for (int i = 0; i < 3; ++i) {
    std::cout << "i = " << i << '\n';
}

Does:

1) Run the expression int i = 0. This creates a new int variable called i with the value 0. Note that because this variable was created within the for statement, it will not be available outside of it.
2) Run the expression i < 3, which will return true if i is less than 3, and false otherwise.
a) If the result is true, run the statements in the block - which in this case is just the single line "std::cout << "i = " << i << '\n';".
b) If the result is false, skip over the block without running the statements (and move on to whatever code follows the for statement).
3) Run the expression ++i, which increments the variable i (adds 1 to whatever value is currently in i).
4) Go to step 2.

This will cause the statement "std::cout << "i = " << i << '\n';" to be executed three times, with i equal to 0, 1, then 2. After the third time, the value of i gets incremented to 3, which causes the test i < 3 to return false (3 is not less than 3), and the looping ends (the program continues on with whatever code follows the for statement).

Generally, to repeat a set of statements N times, you use:

for (int n = /* start-value */ ; n < /* N + start-value */ ; ++n) {
    // statements
}

For example:

#include <iostream>
 
int main()
{
    // Try changing these two values!
    // Just beware of making N too big!
    int START_VALUE = 0;
    int N = 3;
 
    for (int i = START_VALUE; i < N + START_VALUE; ++i) {
        std::cout << "i = " << i << '\n';
    }
}

Output:

i = 0
i = 1
i = 2

Originally, C++ only had the type of for loop described above. C++11 added the "range-based for loop" for arrays and containers, which looks like: for (/*variable-declaration*/ : /*container or array*/)