Topic 48 of 100 Control Flow in C Interactive Tutorial

C do...while Loop: Execute First, Check the Condition Later

11 mins read Last updated: 22 Aug 2026 19,700 views
C Compiler 0.00%

What is C do...while Loop? Core Concept & Direct Summary

Core Objective & Problem Statement

How does the `do...while` loop ensure at least one execution of the loop body, and why is the trailing semicolon required?

Direct Answer Summary

Every loop you've met so far is cautious. for and while check their conditions before daring to run the body — and if the condition fails at the door, the body never executes at all. Cautious is usually smart.

But sometimes caution is the wrong shape for the problem. Think about a menu: you can't ask the user to choose before you've shown them the menu. A password prompt: you can't check the input before you've received it. Some code simply must run once before any condition makes sense.

That's the entire reason do-while exists. It's C's optimist: execute first, ask questions later. The body always runs at least once — guaranteed — and only then does the condition decide whether to go again.

(Suggested image: the hero flowchart — Body FIRST, then condition diamond below it, "true" loops back up to the body, "false" exits. Visually mirror this against the while-loop flowchart from the previous page.)

How Does C do...while Loop Work? In-Depth Mechanics & Architecture

The Syntax

main.c
Run Online
do {
    // body — ALWAYS runs at least once
} while (condition);

Three details to notice:

  1. The body comes first, wrapped in braces after do
  2. The condition comes after, at the bottom
  3. There's a semicolon after while (condition); — required, and forgetting it is one of the most common compile errors beginners hit with this loop

A first example:

main.c
Run Online
int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);
// Output: 1 2 3 4 5

Looks familiar so far. But now watch the difference that defines this loop...


The Guarantee in Action: One Run, No Matter What

main.c
Run Online
int x = 100;
// while version — prints NOTHING:while (x < 10) {    printf("while: x = %d\n", x);    x++;}
// do-while version — prints ONCE despite the false condition:x = 100;do {    printf("do-while: x = %d\n", x);    x++;} while (x < 10);

Output:

The while loop checked first, found 100 < 10 false, and skipped its body entirely. The do-while ran its body before ever checking — so it printed once, then saw the same false condition and stopped. That single guaranteed execution is the whole personality of this loop.

This is why you'll hear them described as:

  • while = entry-controlled loop (check at the door)
  • do-while = exit-controlled loop (check on the way out)

(Suggested image: side-by-side flowchart — "while: gatekeeper BEFORE the room" vs "do-while: gatekeeper AFTER the room")


The Killer Application: Menu-Driven Programs

Ask any C instructor where do-while truly earns its keep, and the answer is unanimous: menus. Show the menu, take the choice, act on it, repeat until the user quits. The menu must appear at least once — the loop's guarantee fits the problem like a glove:

main.c
Run Online
#include <stdio.h>
int main() {
    int choice;
    do {
        puts("\n===== MAIN MENU =====");
        puts("1. Check balance");
        puts("2. Deposit");
        puts("3. Withdraw");
        puts("0. Exit");
        printf("Your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: puts("Balance: ₹5,000.00");
            break;
            case 2: puts("Deposit feature coming!");
            break;
            case 3: puts("Withdraw feature coming!");
            break;
            case 0: puts("Goodbye!");
            break;
            default: puts("Invalid option. Try again.");
        }
    } while (choice != 0);
    return 0;
}

Sample Run:

main.c
Run Online
===== MAIN MENU =====1. Check balance2. Deposit3. Withdraw0. ExitYour choice: 1Balance: ₹5,000.00
===== MAIN MENU =====...Your choice: 0Goodbye!

Look how naturally the pieces fit: do-while guarantees the menu displays, switch handles the choice (remember our switch tutorial — one variable, exact values), and the loop repeats until the sentinel 0 appears. Menu + do-while + switch is a combination you'll see in thousands of student projects and real console applications.

Try writing this with a plain while and you'll immediately feel the friction — you'd have to show the menu once before the loop (duplicated code) or prime choice with a fake value (a hack). do-while says exactly what you mean.


Input Validation: The Natural Second Home

Remember the validation loop from the while tutorial? It needed a "priming read" — the prompt written twice:

main.c
Run Online
// while version — prompt appears TWICE:printf("Enter age (1-120): ");
scanf("%d", &age);
while (age < 1 || age > 120) {
    printf("Invalid! Try again: ");
    scanf("%d", &age);
}

do-while absorbs the first attempt into the loop:

main.c
Run Online
// do-while version — prompt written ONCE:int age;
do {
    printf("Enter age (1-120): ");
    scanf("%d", &age);
    if (age < 1 || age > 120) {
        puts("Invalid! Please try again.");
    }
} while (age < 1 || age > 120);
printf("Age recorded: %d\n", age);

Sample Run:

main.c
Run Online
Enter age(1-120): 500Invalid! Please try again.Enter age(1-120): -3Invalid! Please try again.Enter age(1-120): 28Age recorded: 28

One prompt, one loop, no duplication. Whenever "ask at least once, repeat if wrong" describes your problem, do-while is the idiomatic C answer.


do-while vs while vs for: The Final Verdict

whiledo-whilefor
Condition checkedBefore bodyAfter bodyBefore body
Minimum executions01 (guaranteed)0
Best forCondition-driven, might skip entirelyMust-run-once: menus, prompts, validationCounted repetition
Semicolon after conditionNoYes — required!n/a (header)
Loop family nameEntry-controlledExit-controlledEntry-controlled

The decision question is one sentence long: "Does this code need to run even when the condition is already false?" Yes → do-while. No → while. Counting → for.


The Classic Mistakes

1. Forgetting the semicolon (the signature error of this loop):

main.c
Run Online
do {
    printf("Hello\n");
} while (i < 5) // ✗ compile error — missing semicolon!
} while (i < 5);
// ✓ correct

After a while loop, no semicolon; after do-while, mandatory. Your muscle memory from while will betray you here — everyone gets caught once.

2. Using do-while when zero executions are required:

main.c
Run Online
// DANGER: body runs even for an empty list!do {
process(item);
} while (moreItems());

If the list might be empty, "always run once" becomes a bug, not a feature. That's a while job.

3. Declaring a variable inside the body, then using it in the condition:

main.c
Run Online
do {
    int choice;
    // declared INSIDE    scanf("%d", &choice);
} while (choice != 0);
// ✗ ERROR — choice is out of scope here!

Variables declared in the body die at the closing brace — before the condition is checked. Declare them before the do:

main.c
Run Online
int choice;
// ✓ outside the loop
do {
    scanf("%d", &choice);
} while (choice != 0);

This one surprises even experienced programmers switching from other languages.

4. The missing update — same infinite-loop trap as while:

main.c
Run Online
int i = 1;
do {
    printf("%d ", i);
    // forgot i++ — "1 1 1 1..." forever
} while (i <= 5);

5. The stray semicolon after do:

main.c
Run Online
do;
// ← semicolon makes an empty statement
{
    printf("Hello\n");
} while (i < 5);
// confusing errors follow

(Suggested image: "5 do-while Mistakes" checklist graphic — consistent with the series)


A Complete Example: The Number Guessing Game, Revisited

Remember the guessing game from the Control Flow pillar? Here's a cleaner version that uses do-while plus a "play again" feature — the second place this loop shines:

main.c
Run Online
#include <stdio.h>
int main() {
    char playAgain;
    do {
        int secret = 42, guess, attempts = 0;
        puts("\n=== Guess the number (1-100) ===");
        do {
            printf("Your guess: ");
            scanf("%d", &guess);
            attempts++;
            if (guess < secret) {
                puts("Too low!");
            } else if (guess > secret) {
                puts("Too high!");
            }
        } while (guess != secret);
        printf("Correct! It took %d attempts.\n", attempts);
        printf("Play again? (y/n): ");
        scanf(" %c", &playAgain);
    } while (playAgain == 'y' || playAgain == 'Y');
    puts("Thanks for playing!");
    return 0;
}

Sample Run:

main.c
Run Online
=== Guess the number(1-100) ===
Your guess: 50
Too high!
Your guess: 42
Correct! It took 2 attempts.
Play again?(y/n): n
Thanks for playing!

Two nested do-while loops, each doing its signature job: the inner one guarantees at least one guess, the outer one guarantees at least one game. Plus the space in scanf(" %c") from our scanf tutorial handling the leftover newline. Everything this series has taught, working as one program.


Final Thoughts

do-while is the least-used of C's three loops, but that's because it's specialized, not because it's weak. When the problem says "this has to happen at least once" — menus, prompts, retries, game rounds — no other loop expresses the intent as honestly.

Lock in the essentials: body first, condition after; the trailing semicolon is mandatory; declare condition variables outside the loop; and reach for it when one guaranteed execution is what the problem demands.

With that, your loop toolkit is complete: for counts, while watches, do-while guarantees. One control-flow topic remains: the escape artists — break and continue — which you've already seen in action. Time to give them their own page.

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    int choice = 0;
    // Menu validation example
    do {
        printf("=== System Menu ===\
");
        printf("1. Start Server\
");
        printf("2. Stop Server\
");
        printf("3. Exit\
");
        printf("Selection: ");
        choice = 3;
        // Simulating valid user exit selection
        printf("%d\
", choice);
    } while (choice < 1 || choice > 3);
    printf("Selected Option: %d\
", choice);
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Use do...while for console menu loops and user input validation where user input must be collected before validating.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: Why is `do { ... } while(0)` widely used in C `#define` preprocessor macros?

A: It allows multi-statement macros to be used safely inside `if-else` blocks without causing dangling `else` syntax errors when followed by a semicolon.
Q

Q: What is the minimum number of times a `do-while` loop executes?

A: Exactly 1 time.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations