πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English

Lesson 12: while & do-while Loop

Loops driven by a condition rather than a counter. Pre-test while and post-test do-while.

πŸ“– What to learn on this page
βœ… Must-know essentials
  • while (cond) { ... } runs while the condition is true
  • do { ... } while (cond); runs at least once
  • Don't forget the trailing semicolon on do-while
⭐ Read if you have time
  • Infinite loop while (1) + break to exit
  • Forgetting to update the loop variable causes infinite loops
  • Mechanically, for and while are interchangeable

while — repeat while the condition is true

while is the right fit when you don't know the iteration count up front. The idea is "keep going as long as this condition holds" β€” just like the English word "while."
while (condition) {
    // runs over and over while condition is true
}

Example: how many doublings to pass 100?

int n = 1;
int count = 0;
while (n <= 100) {
    n = n * 2;
    count++;
}
printf("%d steps to reach %d\n", count, n);
// -> 7 steps to reach 128
You can't predict the iteration count ahead of time here, so while fits better than for. The loop repeats: check condition β†’ run body β†’ check condition β†’ …

The evaluation order (pre-test)

1. Check n <= 100
2. If true, run the { ... } body
3. At }, jump back to step 1
4. Once the condition is false, the loop ends
Key idea: because the check happens first, if the condition is already false, the body runs zero times.

for vs while — which should I use?

Mechanically, for and while can be rewritten as each other. Both work β€” pick the one that expresses your intent more clearly.

Same task, two forms

for (count-based)
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}
while (same logic)
int i = 0;
while (i < 5) {
    printf("%d\n", i);
    i++;
}
for puts "init / condition / update" right in the header, so reach for for whenever the iteration count is fixed.

When to use which

SituationBest fitExample
Known iteration countforwalking an array 0..N-1
Stop on a condition (count unknown)whilereading until the user types "q"
Must run at least oncedo-whileprompt for input, re-prompt if invalid
Infinite loop (exit via break)while(1) / for(;;)an event or main loop
⚠️ A common while mistake: forgetting to update the condition variable inside the body. for forces you to put the update in the header, so this class of bug is rarer there.

do-while — guaranteed to run at least once

while checks the condition before the body (pre-test); do-while checks it after the body (post-test). That's why a do-while body always runs at least once.
while (pre-test)
while (cond) {
    body;  // 0 times if cond is false
}
If the condition is false from the start, the body runs zero times.
do-while (post-test)
do {
    body;  // always 1+ times
} while (cond);
Body first, then check β€” one iteration is always guaranteed.
⚠️ Don't forget the trailing semicolon! } while (cond); has to end with ; or the compiler will reject it. This quirk is unique to do-while.

Typical use: prompt and re-prompt until the input is valid

"Enter 1–3, and if the input is invalid keep asking" — you need to show the prompt at least once, so do-while is a natural fit.
int choice;
do {
    printf("Choose 1-3 > ");
    scanf("%d", &choice);
    if (choice < 1 || choice > 3)
        printf("Invalid input\n");
} while (choice < 1 || choice > 3);
printf("You picked %d\n", choice);

while vs do-while — zero-iteration case

while with condition false from the start
int i = 10;
while (i < 5) {
    printf("x");
}
0 iterations (nothing printed)
do-while with condition false from the start
int i = 10;
do {
    printf("x");
} while (i < 5);
1 iteration (prints one "x")

Infinite-loop traps — forgetting to update

The most common while / do-while bug is an infinite loop β€” forgetting to change the condition variable inside the body.
πŸ”΄ Trap 1: forgotten counter update
int i = 0;
while (i < 5) {
    printf("%d\n", i);
    // forgot i++!
}
What happens: i never changes, so i < 5 stays true β€” an infinite loop that prints 0 forever.
Fix: always check that the while body has something moving the loop toward its exit. for makes this harder to miss because the update clause is baked into the syntax.
πŸ’‘ Intentional infinite loop + break
When you want "keep running, and exit on some event," use while (1) with break to get out.
while (1) {          // 1 is always true -> infinite
    int n;
    scanf("%d", &n);
    if (n == 0) break;  // leave on 0
    printf("Got: %d\n", n);
}
This is common in event loops and interactive programs, where break or return is the planned exit.
⚠️ do-while shares the same risk
int choice;
do {
    printf("1-3 > ");
    // forgot scanf! choice stays uninitialized
} while (choice < 1 || choice > 3);
choice never changes, so depending on its initial value the loop may run forever. Make sure every iteration updates the variable the condition tests.
If you get stuck in one: press Ctrl + C to stop a terminal program. In Visual Studio, click "Stop Debugging."

Try it yourself — while loop

my_while.c
Output
Press "Run" to execute...
πŸ’‘ Try these ideas too

Related Lessons

Loops
Lesson 11: for Loop
The counted-iteration form of looping.
Debugging
Debugging Techniques
Practical tips, including how to stop an infinite loop.
Arrays
Arrays
Combine loops and arrays for real data processing.
← Previous
Lesson 11: for Loop
Next →
Lesson 20: Arrays

Review Quiz

Check your understanding.

Q1. What does while(1) do?

Runs once
Infinite loop
Compile error

The condition is always 1 (true), so it loops forever unless a break or return takes you out.

Q2. Difference between do-while and while?

No difference
do-while runs at least once
do-while is faster

do-while checks the condition after the body, so the body always runs at least once. while checks first, so the body may run zero times.

Q3. How many times does this print?

int i = 10;
while (i < 5) {
    printf("x");
    i++;
}
0 (nothing)
Once
5 times
Infinite loop

while is pre-test. With i=10, i<5 is false right away, so the body runs zero times.

Q4. Same condition but as do-while?

int i = 10;
do {
    printf("x");
    i++;
} while (i < 5);
0
Once
5 times
Infinite loop

do-while is post-test: run once, then check. After the first iteration i=11, and 11 < 5 is false, so the loop ends. One iteration β€” the classic "one more than while" behavior.

Q5. What does this code do?

int i = 0;
while (i < 5) {
    printf("%d\n", i);
}
Prints 0..4
Prints 0 once
Prints 0 forever (infinite loop)
Compile error

i++ is missing. i stays at 0 and the condition never becomes false — an infinite loop that prints 0. The most common while bug. Ctrl+C to stop.

Q6. What's the syntax detail you must not forget in do-while?

Parentheses around the condition
Braces {}
The trailing semicolon ;

} while (cond); needs the trailing ; or the compiler rejects it. This rule is unique to do-while.

Share this article
Share on X Share on Facebook