Lesson 57 +10 XP

Do/While Loops

Do/While Loops

The do/while loop is the "at least once" loop: it runs the body first, then checks the condition.

The basic form

C
int i = 0;

do {
    printf("%d\n", i);
    i++;
} while (i < 5);

Output:

Code
0
1
2
3
4

Key difference: always runs once

Even if the condition is false from the start, a do/while runs its body once:

C
int i = 10;
do {
    printf("This prints once!\n");
} while (i < 5);

When is it useful?

Menus that must show at least once, validation that asks until the input is good, and &quot;do this, then check if you should repeat&quot;.

while vs do/while

  • while checks first, may run zero times.
  • do/while runs first, checks after, always runs at least once.

TL;DR

  • do { ... } while (condition); runs the body at least once.
  • The condition is checked after each run.
  • Great for menus and retry patterns.
  • Remember the semicolon after the while!