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

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
  • for and while are interchangeable mechanically

while — repeat while the condition is true

while fits when the iteration count is not known in advance. "Keep going as long as this condition holds." In plain English: "while … do …".
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
We can't predict the iteration count up front, so while fits better than for. The loop repeats: check condition β†’ body β†’ check condition β†’ …

The evaluation order (pre-test)

1. Check n <= 100
2. If true, run the { ... } body
3. At }, go back to step 1
4. When the condition becomes false, the loop ends
Key: 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 converted into each other. Both work β€” pick the one that expresses your intent better.

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 makes the "init / condition / update" triple explicit, so use for whenever the iteration count is fixed.

When to use which

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

do-while — guaranteed to run at least once

while checks the condition before the body (pre-test); do-while checks it after (post-test). That's why the do-while body always executes at least once.
while (pre-test)
while (cond) {
    body;  // 0 times if cond is false
}
If the condition is false initially, body runs zero times.
do-while (post-test)
do {
    body;  // always 1+ times
} while (cond);
Run the body first, then check β€” at least one iteration guaranteed.
⚠️ Don't forget the trailing semicolon! } while (cond); must end with ; or the compiler errors out. Unique to do-while.

Typical use: prompt and re-prompt for valid input

"Enter 1–3, and if invalid keep asking" — you must show the prompt at least once, so do-while fits perfectly.
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, condition false up front
int i = 10;
while (i < 5) {
    printf("x");
}
0 iterations (nothing printed)
do-while, condition false up front
int i = 10;
do {
    printf("x");
} while (i < 5);
1 iteration (one "x" is printed)

Infinite-loop traps — forgetting to update

The most common bug with while / do-while 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 is always true β€” an infinite loop printing 0 forever.
Fix: always double-check that the while body has something that moves toward ending the loop. for makes this harder to miss because the update clause is part of the syntax.
πŸ’‘ Intentional infinite loop + break
When you want "keep running, exit on some event", use while (1) and break to leave.
while (1) {          // 1 is always true -> infinite
    int n;
    scanf("%d", &n);
    if (n == 0) break;  // leave on 0
    printf("Got: %d\n", n);
}
Common in event loops and interactive programs, where break / return is the planned way out.
⚠️ 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 can run forever. Make sure the variable the condition tests is updated every iteration.
If you hit one: Ctrl + C stops a terminal program. In Visual Studio, use the "Stop Debugging" button.

Try it yourself — while loop

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

Related Lessons

Loops
Lesson 11: for Loop
The counted-iteration form of loops.
Debugging
Debugging Techniques
Practical tips including stopping infinite loops.
Arrays
Arrays
Combine loops and arrays for real data processing.
← Previous
Lesson 11: for Loop
Next →
Lesson 13: Arrays

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 exits the loop.

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 can 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. i=10 fails i<5 immediately, 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 behaviour.

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 0 and the condition never becomes false — infinite loop printing 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); requires the trailing ; or the compiler rejects it. A do-while-only rule.

Share this article
Share on X Share on Facebook