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:
int i = 0;
while (i < 10)
{
std::cout << i << " ";
++i; // Increment counter
}
std::cout << std::endl; // End of line; "0 1 2 3 4 5 6 7 8 9" is printed to the console
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.