Concept Flow - Do–while loop
Start
Execute body
Check condition
Exit
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 { System.out.println(i); i++; } while (i <= 3);
| Step | i value | Condition (i <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | true | Print 1, increment i to 2 | 1 |
| 2 | 2 | true | Print 2, increment i to 3 | 2 |
| 3 | 3 | true | Print 3, increment i to 4 | 3 |
| 4 | 4 | false | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | 1 | 2 | 3 | 4 | 4 |
do-while loop syntax:
do {
// code
} while (condition);
Runs loop body first, then checks condition.
Repeats if condition true, stops if false.
Always runs at least once.