Table of Contents
A do-while loop repeatedly executes a block of statements while its controlling condition evaluates to true. Unlike a while loop, the condition is evaluated after the loop body, ensuring that the body executes at least once.
The do-while loop is useful when an operation must be performed before its continuation condition can be evaluated, such as displaying a menu or accepting user input.
Source Code #
#include <iostream>
int main()
{
int count = 1;
do
{
std::cout << "Count: " << count << '\n';
++count;
}
while (count <= 5);
return 0;
}
Output #
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation #
dobegins the loop body.- The statements inside the
doblock are executed before the condition is evaluated. std::coutdisplays the current value ofcount.++countincrementscountby one after each iteration.while (count <= 5)evaluates the loop condition after the loop body has executed.- If the condition evaluates to
true, the loop body executes again. - If the condition evaluates to
false, the loop terminates. - Because the condition is checked after the loop body, a
do-whileloop always executes its body at least once. - The semicolon after
while (count <= 5);is required syntax for ado-whilestatement. return 0;terminates the program successfully.