while Loop (C++)
A while loop in C++ repeats a block of code as long as its condition stays true. It is used when you don't know in advance how many times you'll need to loop.
C++
The condition is checked before each pass, so the body may run zero times if the condition starts out false. Make sure something inside the loop eventually makes the condition false to avoid an infinite loop.
A related form, do-while, checks the condition after the body, guaranteeing it runs at least once.
Syntax
while (condition) { /* body */ }Examples
C++
#include <iostream>
int main() {
int count = 0;
while (count < 3) {
std::cout << count << std::endl;
count++;
}
return 0;
}Output:
0
1
2