for Loop (C++)

A C++ for loop repeats a block of code a controlled number of times. Its header has three parts: an initializer, a condition to keep looping, and an update that runs after each pass.

C++

The three parts run in a fixed order: the initializer once at the start, then the condition is checked before each iteration, and the update runs at the end of each iteration.

C++ also offers a range-based for loop (for (auto x : container)) that iterates directly over the elements of an array, vector, or other container.

Syntax

for (init; condition; update) { /* body */ }

Examples

C++

#include <iostream>

int main() {
    for (int i = 0; i < 3; i++) {
        std::cout << i << std::endl;
    }
    return 0;
}

Output:

0
1
2

Learn it in a lesson

See also

Back to the Dictionary