A while loop is a straightforward loop and is also an entry-control loop. It evaluates the condition before executing the block of the loop. If the condition is found to be true, only then the body of the loop is executed. The loop continues until the condition stated found to be false.
While loops are used when we do not know the exact number of times the iteration required beforehand. By default the while loop condition is true.
while loop Flowchart:

The syntax for while loop
in C++:
1 2 3 4 | while(condition) { //block of code to be executed } |
You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.
Example of C++ while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> using namespace std; int main() { int i = 1; // while loop while (i <= 10) { cout << "value of i: " << i << endl; i++; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 | value of i: 1 value of i: 2 value of i: 3 value of i: 4 value of i: 5 value of i: 6 value of i: 7 value of i: 8 value of i: 9 value of i: 10 |