Skip to content
FollowtheDamnCode

The do-while Loop

Run once, then keep repeating.

3 minute read

Big idea

A do-while loop runs its block first, then checks the condition β€” so the block always runs at least once.

The idea

do {
    // runs once, then again while the condition is true
} while (condition);

Compare the two loops when the condition is false from the start:

Predict: which loop prints?
#include <stdio.h>

int main(void) {
    int n = 10;
    while (n < 5) {
        printf("while ran\n");
    }
    do {
        printf("do-while ran\n");
    } while (n < 5);
    return 0;
}
What does it print? Show the answer
do-while ran

Run and edit it in the app.

The while checks first, sees 10 < 5 is false, and never runs. The do-while runs its block, then checks.

Note the semicolon after while (condition); β€” do-while is the one loop that needs it.

Where it fits

Anything that must happen once before you can decide whether to repeat β€” the classic is asking until the answer is valid:

Ask again until the number is between 1 and 10
#include <stdio.h>

int main(void) {
    int n;
    do {
        printf("Pick 1-10: ");
        scanf("%d", &n);
    } while (n < 1 || n > 10);
    printf("\nYou picked %d\n", n);
    return 0;
}
input
42
-3
7
output
Pick 1-10: Pick 1-10: Pick 1-10: 
You picked 7

Run and edit it in the app.

The input has three answers, one per line. The first two are rejected, so the prompt appears three times. (When you type into a real terminal, each prompt waits for you.)

Watch it

Think of it like

Tasting food while you cook. You always take the first taste β€” then decide whether it needs more salt and another taste.

πŸ•·οΈ Spidey-sense: do { try_the_door(); } while (door_locked); β€” I always try the door at least once. Knocking politely is underrated.

Key terms

  • do-while β€” A loop that checks its condition after each round.
  • Post-test loop β€” Another name for it: the test comes after the body. while and for are pre-test loops.

Check yourself

How many times does a do-while body run at minimum?

Which needs a semicolon after its condition?

A good use for do-while is…