Control Structure

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

  1. Run loop body once immediately.
  2. Check condition after the body.
  3. If condition is true, run body again.
  4. Continue until condition becomes false.

Post-Condition Concept

`Post-condition` means the check happens after execution. That is the main difference from while.

StepblinkCountAction
10Run body first
21Check condition (true)
32..4Repeat body + check
Stop5Condition 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

  1. blinkCount is reset to 0 at start of loop().
  2. Inside do block, LED turns ON, logs, waits, then turns OFF.
  3. blinkCount increments at end of each cycle.
  4. Condition blinkCount < 5 is checked after cycle execution.
  5. 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

  1. LED pin goes HIGH, so hardware LED turns ON.
  2. Serial outputs current loop cycle number for debugging visibility.
  3. A delay holds ON state so the learner can visually observe it.
  4. LED pin goes LOW, turning hardware LED OFF.
  5. Second delay holds OFF state before next step.
  6. blinkCount is increased to move toward loop exit.
  7. Condition is evaluated after body execution.
  8. If condition true, control jumps back to the top of do block.

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

  1. Change loop limit from 5 to 3 and observe cycle count differences.
  2. Print a message before and after increment to track internal state.
  3. Add a safety variable that force-stops after max attempts.
  4. 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.

Run in Simulator