For in C++

#include <iostream>

int main() {
    // The most basic type, with a single condition.
    int i = 1;
    while (i <= 3) {
        std::cout << i << std::endl;
        i = i + 1;
    }

    // A classic initial/condition/after for loop.
    for (int j = 0; j < 3; j++) {
        std::cout << j << std::endl;
    }

    // Another way of accomplishing the basic "do this N times" iteration
    // is to use a range-based for loop with an array.
    int arr[] = {0, 1, 2};
    for (int i : arr) {
        std::cout << "range " << i << std::endl;
    }

    // A loop without a condition will run indefinitely until you break
    // out of the loop or return from the enclosing function.
    while (true) {
        std::cout << "loop" << std::endl;
        break;
    }

    // You can also continue to the next iteration of the loop.
    for (int n = 0; n < 6; n++) {
        if (n % 2 == 0) {
            continue;
        }
        std::cout << n << std::endl;
    }

    return 0;
}

for is C++’s primary looping construct, but it also supports while and do-while loops. Here are some basic types of loops in C++.

The most basic type is a while loop with a single condition.

A classic for loop in C++ has three components: initialization, condition, and iteration.

C++11 introduced range-based for loops, which can be used to iterate over elements in an array, vector, or other container.

C++ also supports infinite loops using while(true) or for(;;). You can use break to exit the loop or return to exit the function.

You can use continue to skip to the next iteration of the loop.

To run the program, save it as for_example.cpp and compile it using a C++ compiler:

$ g++ -std=c++11 for_example.cpp -o for_example
$ ./for_example
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

C++ offers various looping constructs, and we’ll see more examples when we look at containers, algorithms, and other data structures.