while loop
suggest changeA 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:
// :glot
#include <iostream>
auto main() -> int
{
int i = 0;
while (i < 10)
{
std::cout << i << " ";
++i;
}
std::cout << '\n';
}
0 1 2 3 4 5 6 7 8 9
Unlike if and switch, a while statement does not have a separate
initializer. To restrict the counter's lifetime, put the declaration and loop
in their own scope:
{
int i = 0;
while (i < 10) {
// ...
++i;
}
}
To create an infinite loop, the following construct can be used:
while (true)
{
// Do something forever (however, you can exit the loop with break)
}
There is another variant of while loops, namely the do...while construct. See the do-while loop example for more information.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents