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.
int i = 1; do { cout << i << " "; i++; } while (i <= 3);
| Step | i value | Condition (i <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | true | Print 1, i = i + 1 (i=2) | 1 |
| 2 | 2 | true | Print 2, i = i + 1 (i=3) | 2 |
| 3 | 3 | true | Print 3, i = i + 1 (i=4) | 3 |
| 4 | 4 | false | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | 1 | 2 | 3 | 4 | 4 |
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.