The do/while
loop in C++ is a variation of the while
loop that ensures the code block executes at least once before the condition is checked. This makes it useful for situations where the initial execution must occur regardless of the condition’s result.
How the do/while Loop Works
Unlike the while
loop, which checks the condition before running its block, the do/while
loop executes the block first and evaluates the condition afterwards.
Syntax
do { // Code block executes at least once } while (condition);
Example: Counting Laps on a Track
This program counts laps and guarantees the first lap gets counted, even if the condition is false.
#include <iostream> using namespace std; int main() { int lap = 0; do { cout << "Lap number: " << lap << "\n"; lap++; } while (lap < 3); // Loop repeats until lap is 3 or greater return 0; }
How the Example Works
- The variable
lap
starts at 0. - The loop runs once, prints the lap number, and increments
lap
. - After the code block executes, the condition (
lap < 3
) is checked. If true, the loop repeats. - Once
lap
reaches 3, the condition becomes false, and the loop stops.