Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 135 ยท Control Flow

while and do-while Loops

Learn how while and do-while loops work in C, how to read input until EOF or a sentinel value, validate input with retries, and avoid infinite loops.

A loop runs the same block of code again and again while some condition holds. Without loops, a program that adds up 1,000 numbers would need 1,000 lines. With a loop it needs four. C has three loop statements: while, do-while and for. This lesson covers the first two, which are the natural choice when you don't know in advance how many times the loop will run: reading input until it runs out, retrying until the user types something valid, or repeating a calculation until a result is good enough.

You'll learn exactly when each condition is checked, how to write the input loops that almost every C program contains, how sentinel values work, and how to spot (and deliberately write) infinite loops. The for loop gets its own lesson next.

The while loop

A while loop checks its condition before every pass through the body:

C
while (condition) {
    /* body: runs as long as condition is true (nonzero) */
}

The steps are always the same:

  1. Evaluate condition.
  2. If it is false (zero), skip the body and continue after the loop.
  3. If it is true (any nonzero value), run the body, then go back to step 1.

Each run of the body is called an iteration. Because the check comes first, a while body can run zero times. As you saw in Booleans, C treats any nonzero value as true, so while (n) means "while n is not zero".

C Count down with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first loop prints 5... down to 1.... When seconds reaches 0, the condition seconds > 0 is false, so the loop ends and Liftoff! appears. The second loop's condition is false from the start, so its body never runs.

Every useful while loop needs three ingredients:

  • Initialization before the loop (int seconds = 5;).
  • A condition that is checked each time (seconds > 0).
  • An update inside the body that eventually makes the condition false (seconds--).

Forget the update and the loop never ends. That trio is so common that the for loop packs all three into one line; you'll see it in the next lesson.

Always use braces, even for a one-line body. Without them, only the first statement belongs to the loop. while (n > 0) printf("%d\n", n); n--; looks like a two-line body, but n-- is outside the loop, so the loop prints forever. This is the same trap you met with if statements.

Loops that compute

A while loop is the natural tool when the number of steps depends on the data. A classic example is processing the digits of a number: you keep dividing by 10 until nothing is left, and you can't know beforehand how many digits there are.

C Digits of a number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

For 9075123 the program reports 7 digits, a digit sum of 27 and the reversed number 3215709. The % and / operators from Arithmetic Operators do the real work: rest % 10 is the last digit and rest / 10 removes it.

Notice that the loop works on a copy (rest), so the original n survives for printing. Also try n = 0: the loop runs zero times and reports 0 digits. Whether 0 "has one digit" is a decision your program has to make explicitly, which is exactly the kind of case a do-while handles well.

The do-while loop

A do-while loop checks its condition after the body:

C
do {
    /* body: always runs at least once */
} while (condition);

The body runs first, then the condition decides whether to go around again. So a do-while body always runs at least once. Note the semicolon after the closing parenthesis; leaving it out is a compile error.

Use do-while when the first pass must happen before there is anything to test. Counting digits is a good example: every number, including 0, has at least one digit.

C do-while runs at least once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

0 has 1 digit(s) comes out right with no special case, because the body runs once before n > 0 is checked. The last sample is the largest 64-bit unsigned long, which has 20 digits. (The small for loop in main just runs the function five times; for Loops explains it, and Functions explains count_digits.)

while or do-while?

Question while do-while
When is the condition checked? Before each iteration After each iteration
Minimum number of iterations 0 1
Typical use Processing data that might be empty Menus, retry-until-valid input, "do it, then decide"
Semicolon after ) No Yes, required

In practice, while is far more common. Reach for do-while only when "at least once" is truly part of the logic.

Input loops

Most C programs read input in a loop: "keep reading until there's nothing left". The key fact from Reading Input with scanf and fgets is that every input function tells you whether it succeeded. scanf returns how many values it stored (or EOF), fgets returns NULL at the end of input, and getchar returns EOF. You put that check right in the loop condition.

C Sum numbers until EOF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The Input box holds five numbers, so the program prints read 5 numbers, total 60, average 12.00. When input runs out, scanf returns EOF (a negative value), the condition == 1 is false, and the loop ends. If you type a word like ten into the Input box, scanf returns 0 because it can't convert it, and the loop also stops. Comparing with == 1 rather than != 0 matters: while (scanf(...)) would treat EOF (usually -1) as true and loop forever.

When you run a program in a terminal, you signal "end of input" by pressing Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows. In our editor, the end of the Input box is the end of input.

The same pattern works one character at a time with getchar. Note that c must be an int, not a char, so it can hold every character value and the distinct value EOF:

C Count lines and characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The condition (c = getchar()) != EOF does two things: it assigns the next character to c, then compares the result with EOF. The extra parentheses are essential, because != binds tighter than = (see Operator Precedence). Without them, c would get the result of the comparison, 0 or 1. The program reports 36 characters and 4 lines. Newlines are characters too, and the editor ends the input with one, just as pressing Enter would. The blank third line counts as a line, and the last check makes sure a final line without a newline (common in files) is still counted.

Sentinel values

A sentinel is a special input value that means "stop", such as 0, -1 or the word quit. It's useful when the input stream itself keeps going, for instance when a person is typing at a terminal. The loop must check for the sentinel after reading a value but before processing it. A loop whose exit sits in the middle of the body like this is often written as while (1) with a break, which the lesson on break, continue and goto covers in depth.

C Stop at the sentinel 0

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Here the read and the sentinel test fit into a single condition, thanks to && short-circuiting: if scanf fails, score != 0 is never evaluated, so the program never looks at an unset variable. The output is 3 scores, highest 80, and the 999 after the sentinel is never read. Choose a sentinel that can't be a real data value; if 0 were a valid score, you'd pick -1 or a word instead.

Validating input with do-while

A retry loop is the textbook use of do-while: ask once, and ask again while the answer is unusable. Reading whole lines with fgets and converting them with sscanf keeps bad input from getting stuck in the input stream:

C Ask until the answer is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

twelve, 0 and 15 are rejected, 7 is accepted, and the loop ends. The strcspn line cuts off the newline that fgets keeps at the end of the line; String Functions explains it. The NULL check inside the loop handles input that ends before a valid answer arrives. Delete the 7 from the Input box to see it: without that check, a do-while waiting for valid input would spin forever on a closed input stream.

Infinite loops

A loop whose condition never becomes false is an infinite loop. Sometimes it's a bug:

C
int i = 0;
while (i < 10) {
    printf("%d\n", i);
    /* BUG: forgot i++ */
}

unsigned int u = 10;
while (u >= 0) {    /* BUG: an unsigned value is always >= 0 */
    u--;            /* after 0 it wraps to 4294967295 */
}

The second one is sneaky: unsigned numbers wrap around instead of going negative (see Integer Types), so u >= 0 is always true. GCC catches this with -Wextra, which our editor uses: it warns comparison of unsigned expression in '>= 0' is always true. Read your warnings; they find bugs like this for free.

Sometimes an infinite loop is exactly what you want. Servers, embedded firmware and game loops run "forever" and leave through a break, a return or by ending the program:

C
while (1) {          /* or for (;;) โ€” both are idiomatic C */
    read_sensor();
    update_display();
}

In C23, while (true) works without any header; in C99 to C17 you need #include <stdbool.h> for true.

If a program in our editor loops forever, the server stops it after a few seconds and shows a time-limit note. On your own computer, press Ctrl+C in the terminal to stop a runaway program.

Common mistakes

  • A stray semicolon: while (n > 0); ends the loop statement right there. The empty statement ; becomes the body, and the braces below run once afterwards, if the loop ever ends. GCC doesn't always warn, so look for it when a loop "hangs".
  • = instead of ==: while (answer = 'y') assigns, so it's always true. GCC suggests parentheses around an assignment used as a truth value.
  • Using char for getchar(): a char can't reliably hold EOF, so the loop may never end or may stop early on a special byte.
  • Testing feof in the loop condition: while (!feof(stdin)) checks for end of input before trying to read, so the last value is often processed twice. Test the read function's return value instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int n = 3; while (n > 0) { printf("%d ", n); n -= 2; }

    n is 3 (printed), then 1 (printed), then -1, which fails n > 0, so the loop stops after printing 3 and 1.
  2. 2. What does this print? int n = 0; do { printf("x"); } while (n > 0);

    A do-while runs its body once before checking the condition, so x is printed once; then n > 0 is false and the loop ends.
  3. 3. Why should the variable that stores getchar() be an int?

    getchar returns either a character as an unsigned char value or EOF, which is negative. A char can't represent all of those distinctly, so the EOF test can fail.
  4. 4. With input 5 8 x 3, how many numbers does while (scanf("%d", &v) == 1) count++; count?

    scanf reads 5 and 8, then fails to convert x and returns 0, which ends the loop. The 3 is never read.
  5. 5. Why does unsigned int u = 5; while (u >= 0) { u--; } never end?

    Unsigned arithmetic wraps, so 0 - 1 becomes the maximum value and the condition stays true forever. GCC warns that the comparison is always true.

Summary

  • while (condition) { ... } checks the condition before each iteration, so the body may run zero times.
  • do { ... } while (condition); checks after each iteration, so the body runs at least once. The final semicolon is required.
  • A working loop needs initialization, a condition and an update that eventually makes the condition false.
  • Put the input function's result in the loop condition: while (scanf("%d", &x) == 1), while (fgets(...) != NULL), while ((c = getchar()) != EOF) with int c.
  • A sentinel value ends input that would otherwise keep going; check it after reading and before processing.
  • while (1) and for (;;) are deliberate infinite loops; an unexpected one usually means a missing update, = instead of ==, or an unsigned value compared with >= 0.

Next: for Loops, where initialization, condition and update move into a single line.