Table of Contents
A while loop repeatedly executes a block of statements as long as its controlling condition evaluates to true. The condition is evaluated before each iteration, so the loop body may execute zero or more times depending on the initial condition.
The while loop is useful when the number of iterations is not known in advance and execution should continue while a specific condition remains satisfied.
Source Code #
#include <iostream>
int main()
{
int count = 1;
while (count <= 5)
{
std::cout << "Count: " << count << '\n';
++count;
}
return 0;
}
Output #
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation #
whilebegins awhileloop.- The condition
count <= 5is evaluated before each iteration. - If the condition evaluates to
true, the statements inside the loop body are executed. std::coutdisplays the current value ofcount.++countincrementscountby one after each iteration.- When
countbecomes6, the conditioncount <= 5evaluates tofalse. - The loop terminates and execution continues with the statement following the loop.
- If the condition is initially
false, the loop body is not executed. return 0;terminates the program successfully.