C/C++ Arena

Step 5 of 7

do-while

while and for check their condition before each pass. do ... while checks it after, so the body always runs at least once:

do {
    body
} while (condition);

Note the semicolon after the closing parenthesis; forgetting it is a compile error.

This fits situations where you must do something before you can decide whether to repeat, such as asking for input and then checking it:

#include <stdio.h>

int main(void) {
    int guess;
    int tries = 0;
    do {
        scanf("%d", &guess);
        tries++;
    } while (guess != 42);
    printf("got it in %d tries\n", tries);
    return 0;
}
10 50 42 7
got it in 3 tries

With a plain while, you'd need to read once before the loop and again inside it, repeating code. do-while avoids that.

Validation loops

"Keep asking until the input is valid" is the classic use. The condition describes invalid input, so the loop repeats while the input is bad. Write the condition carefully: "less than 1 or greater than 5" is outside the range; "less than 1 and greater than 5" can never be true, so the loop would never repeat.

Your turn: read numbers until one is between 1 and 5 (inclusive). For every invalid number print invalid N. Then print chose N.

Previous: break and continue Next: Nested loops