while loop

suggest change

A while loop executes statements repeatedly until the given condition evaluates to false. This control statement is used when it is not known, in advance, how many times a block of code is to be executed.

For example, to print all the numbers from 0 up to 9, the following code can be used:

#include <iostream>
using namespace std;

auto main() -> int
{
    int i = 0;
    while (i < 10)
    {
        std::cout << i << " ";
        ++i;
    }
    std::cout << std::endl;
}
0 1 2 3 4 5 6 7 8 9 

Note that since C++17, the first 2 statements can be combined

while (int i = 0; i < 10) {
	//... The rest is the same
}

To create an infinite loop, the following construct can be used:

while (true)
{
    // Do something forever (however, you can exit the loop by calling 'break'
}

There is another variant of while loops, namely the do...while construct. See the do-while loop example for more information.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents