C do-while Loop

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is a do-while Loop?

A do-while loop is a post-test loop: it runs the body first, then checks the condition. The body always executes at least once. Contrast with while, which may skip the body entirely.

Remember
do {
    /* body — runs first */
} while (condition);   /* semicolon required */

body runs at least once
then repeats while condition is true

while  → test first  (0+ times)
do-while → test after (1+ times)
UsePrefer
Must run body once firstdo-while
May skip body entirelywhile
Counted repeats with init/updatefor

How to Use do-while in C

Write the body, end with while (condition);, and make sure something in the body moves toward stopping.

  1. Open with do { and put the work inside the braces.
  2. Close with } while (condition); — keep the semicolon.
  3. Update the variables the condition uses (counter, input, flag).
  4. Compile with gcc file.c -std=c11 -o out and run.
PieceRequired?Role
do { ... }YesBody that runs before the first test
while (condition)YesExit test after each pass
Trailing ;YesEnds the do-while statement

Pseudocode

Pseudocode
set starting values

do:
    run the body
    update counters / read input / change flag
while condition is true

// after exit: condition was false
// note: body already ran at least once

Cheat Sheet

Keep these facts handy while writing post-test loops.

TopicDetail
Syntaxdo { ... } while (expr);
Test timingAfter the body (post-test)
Minimum runs1
vs whilewhile can run 0 times
Common usesMenus, “try again”, input checks
Exit earlybreak / continue
Truthy tipAny non-zero int is true; 0 is false

Live Preview

Trace a small do-while in the browser. Same control flow as the C examples below.

Browser simulation of do-while control flow (same idea as the C examples).

Result
i = 0
do { print i; i++ } while (i < 3)

pass 1: print 0 → i=1 → test true
pass 2: print 1 → i=2 → test true
pass 3: print 2 → i=3 → test false → stop

output: 0 1 2

Worked Walkthrough — Count 0, 1, 2

Walk one iteration at a time for do { printf("%d ", i); i++; } while (i < 3); with i starting at 0.

Calculation
start: i = 0

1) body: print 0, then i = 1
   test: 1 < 3 → true → repeat

2) body: print 1, then i = 2
   test: 2 < 3 → true → repeat

3) body: print 2, then i = 3
   test: 3 < 3 → false → exit

output: 0 1 2
If you started with i = 5, the body would still print 5 once.

C Examples

Compile with gcc file.c -std=c11 -o out. Pair with while and for when choosing a loop style.

Example 1 — Print Numbers 0 to 2

A small counter shows the normal path: body, update, then test.

C
#include <stdio.h>

int main(void) {
    int i = 0;

    do {
        printf("%d ", i);
        i++;
    } while (i < 3);

    printf("\n");
    return 0;
}

How It Works

  1. Start at 0. i is initialized before the loop.
  2. Print then bump. Each pass prints i, then does i++.
  3. Test after the body. Continue while i < 3.
  4. Stop at 3. After printing 2, i becomes 3 and the loop ends.

Example 2 — Body Runs Even When Condition Starts False

This is the key difference from while: the body still runs once.

C
#include <stdio.h>

int main(void) {
    int i = 5;

    do {
        printf("body ran with i = %d\n", i);
        i++;
    } while (i < 3);

    printf("after loop, i = %d\n", i);
    return 0;
}

How It Works

  1. Start already “too big”. i = 5 would fail a while (i < 3) test immediately.
  2. Body still runs. do-while prints before any test.
  3. Then the test fails. After i++, 6 < 3 is false → exit.
  4. Takeaway. Prefer do-while only when that first forced pass is what you want.

Example 3 — Keep Asking Until Input Is Valid

Classic use: show a prompt, read a value, repeat until it is in range. Uses if inside the loop.

C
#include <stdio.h>

int main(void) {
    int n;

    do {
        printf("Enter a number from 1 to 10: ");
        if (scanf("%d", &n) != 1) {
            return 1;
        }
    } while (n < 1 || n > 10);

    printf("Accepted: %d\n", n);
    return 0;
}

How It Works

  1. Prompt first. The message and scanf sit in the body so they always run once.
  2. Check the read. If scanf fails, exit with an error code.
  3. Repeat on bad range. n < 1 || n > 10 keeps the loop going.
  4. Accept a good value. When n is 1–10, the condition is false and you print it.

Edge Cases & Pitfalls

Check these before using do-while in real programs.

syntax

Missing semicolon

} while (cond) without ; does not compile. The semicolon belongs to the statement.

update

Forgot to update the condition

If nothing in the body changes the tested variables, you get an infinite loop. Trace the condition each pass.

choice

Used when zero runs were fine

If the body must be skippable, use while or for instead.

input

Bad scanf leaves junk

Failed reads can leave the stream dirty and loop forever. Check the return value and clear input when needed.

Performance Notes

ApproachCostBest for
do-whileSame order as while/forGuaranteed first pass + exit test
while / forSame (loop overhead is tiny)Pre-test or counted loops
Work inside the bodyUsually the real costI/O, heavy math, allocations

Loop choice is about clarity, not micro-speed. Prefer the form that matches “must run once” vs “maybe zero times.” Nested work dominates cost — see nested loops when you scale up.

Key Takeaways

  • Role: post-test loop — body first, condition after.
  • Guarantee: the body runs at least once.
  • Syntax: end with while (cond); — semicolon required.
  • Use when: menus, prompts, and validation need a first pass.

One line: do-while means “do this, then ask whether to do it again.”

Frequently Asked Questions

A do-while loop runs its body at least once, then checks the condition. Syntax: do { ... } while (condition); The semicolon after the closing parenthesis is required.
while tests before the body—the body may run zero times. do-while tests after the body—the body always runs at least once. Use do-while when the first pass must happen before you can decide whether to continue.
The do-while statement ends with while (expression); — that semicolon is required syntax. Leaving it out is a compile error.
Use do-while for prompts, menus, and input validation where you must show or read something once before testing the stop condition.
Yes. If the condition is false after the first execution, the loop exits. Minimum is one run; it continues only while the condition stays true.
No. while (1) loops forever unless you break. do-while always evaluates a real condition after each pass and is the clear choice for guaranteed first execution plus an exit test.

Next: C Math

Explore math functions and numeric helpers in C.

C Math tutorials →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful