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:


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.