Lesson 23 - Using do...while Loop
Learn how do...while runs the loop body at least once, then checks the condition.
Progress indicator
Lesson 23 of 28
Learning Objectives
- Understand what do...while loop is and how it differs from while.
- Write correct do...while syntax with semicolon placement.
- Explain post-condition behavior (run first, check later).
- Identify infinite loop risks and prevent them safely.
- Read nested do...while flow in beginner-friendly steps.
- Trace what happens internally on every loop cycle.
Concept Explanation
What is do...while Loop
A do...while loop repeats code like other loops, but it always runs the loop body once before checking the condition.
This makes it useful when at least one execution is required.
do...while Syntax
do {
// code block
} while (condition);Important: the condition line ends with a semicolon.
How do...while Works
- Run loop body once immediately.
- Check condition after the body.
- If condition is true, run body again.
- Continue until condition becomes false.
Post-Condition Concept
`Post-condition` means the check happens after execution. That is the main difference from while.
| Step | blinkCount | Action |
|---|---|---|
| 1 | 0 | Run body first |
| 2 | 1 | Check condition (true) |
| 3 | 2..4 | Repeat body + check |
| Stop | 5 | Condition false, exit loop |
do...while vs while (Comparison)
while: checks first, may run zero times.do...while: runs first, then checks.- Use do...while when at least one run is required.
Infinite Loop Risk
If condition never becomes false, loop can run forever. Always update control variables.
On real ESP32 hardware, this can block later code and make the program look frozen.
Nested do...while Loops
You can place one do...while inside another, but keep it simple to avoid confusion.
int row = 0;
do {
int col = 0;
do {
col++;
} while (col < 3);
row++;
} while (row < 2);When to Use do...while
- Menu/input logic that must run once before checking exit
- Retry operations where first attempt is mandatory
- One guaranteed sensor read before condition-based repetition
Example Code
This example blinks LED using do...while so one cycle always runs first.
const int ledPin = 2;
int blinkCount = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
blinkCount = 0;
do {
digitalWrite(ledPin, HIGH);
Serial.print("do...while cycle: ");
Serial.println(blinkCount);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
blinkCount = blinkCount + 1;
} while (blinkCount < 5);
Serial.println("do...while loop finished");
delay(1000);
}Example Code Explanation
blinkCountis reset to 0 at start ofloop().- Inside
doblock, LED turns ON, logs, waits, then turns OFF. blinkCountincrements at end of each cycle.- Condition
blinkCount < 5is checked after cycle execution. - When condition is false, loop exits and completion message is printed.
Real-life example
Device setup menus often use do...while so the menu shows at least once before checking whether the user wants to continue.
What Code Happens Inside
- LED pin goes HIGH, so hardware LED turns ON.
- Serial outputs current loop cycle number for debugging visibility.
- A delay holds ON state so the learner can visually observe it.
- LED pin goes LOW, turning hardware LED OFF.
- Second delay holds OFF state before next step.
blinkCountis increased to move toward loop exit.- Condition is evaluated after body execution.
- If condition true, control jumps back to the top of
doblock.
Internal flow rule
execute body -> update state -> check condition -> repeat or exit
Common Mistakes with do...while
- Forgetting semicolon after
while (condition);. - Not updating loop variables, causing infinite loop.
- Using complex conditions that are hard to debug.
- Misunderstanding that do...while always executes at least once.
Best Practices for do...while
- Keep loop conditions readable and explicit.
- Always include a clear exit path.
- Use counters/timeouts for safety when testing.
- Log variable values in Serial while debugging loop flow.
- Keep one clear counter/flag responsible for loop exit.
Practice Task
- Change loop limit from 5 to 3 and observe cycle count differences.
- Print a message before and after increment to track internal state.
- Add a safety variable that force-stops after max attempts.
- Convert this do...while example into while and compare behavior when count starts at 5.
Try it now
Open simulator workspace and compare do...while behavior with while loop.