0
0
C++programming~10 mins

Do–while loop in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Do–while loop
Start
Execute body
Check condition
Yes| No
Repeat
The do-while loop runs the code inside the loop first, then checks the condition. If true, it repeats; if false, it stops.
Execution Sample
C++
int i = 1;
do {
  cout << i << " ";
  i++;
} while (i <= 3);
Prints numbers 1 to 3 using a do-while loop that runs the body before checking the condition.
Execution Table
Stepi valueCondition (i <= 3)ActionOutput
11truePrint 1, i = i + 1 (i=2)1
22truePrint 2, i = i + 1 (i=3)2
33truePrint 3, i = i + 1 (i=4)3
44falseExit loop
💡 At step 4, i is 4, condition 4 <= 3 is false, so loop stops.
Variable Tracker
VariableStartAfter 1After 2After 3Final
i12344
Key Moments - 3 Insights
Why does the loop body run even when the condition is false initially?
Because in a do-while loop, the body runs first before the condition is checked, as shown in step 1 of the execution_table.
When does the condition get checked in a do-while loop?
The condition is checked after the loop body runs, as seen after each action in the execution_table rows.
What happens when the condition becomes false?
The loop stops immediately after the condition check fails, as shown in step 4 where the condition is false and the loop exits.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at step 3?
A2
B3
C4
D1
💡 Hint
Check the 'i value' column at step 3 in the execution_table.
At which step does the condition become false and the loop stops?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look at the 'Condition' column in the execution_table to find when it is false.
If the initial value of i was 5, how many times would the loop body run?
A1 time
B5 times
C0 times
DInfinite times
💡 Hint
Remember do-while runs the body once before checking condition; see key_moments about initial run.
Concept Snapshot
do {
  // code to run
} while (condition);

- Runs loop body first, then checks condition.
- Repeats if condition true, stops if false.
- Executes at least once even if condition false initially.
Full Transcript
A do-while loop in C++ runs the code inside the loop first, then checks the condition. If the condition is true, it repeats the loop. If false, it stops. This means the loop body always runs at least once. For example, starting with i=1, the loop prints i and increases it by 1, then checks if i is less or equal to 3. It repeats until i becomes 4, then stops. This is different from a while loop that checks condition before running the body. The execution table shows each step with i's value, condition result, action taken, and output. The variable tracker shows how i changes after each iteration. Key moments clarify why the body runs first and when the loop stops. The quiz tests understanding of i's value at steps, when the loop ends, and behavior with different initial values.