Part of C in 100s

C in 100 Seconds: While Loops | Episode 7

Celest KimCelest Kim

Video: C in 100 Seconds: while vs do-while — Two Ways to Loop | Episode 7 by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

C While vs Do-While: Two Ways to Loop

while (cond) { ... } checks first. do { ... } while (cond) checks last (always runs at least once). Pick based on whether the body should run when the condition starts false.

C has three loop forms: for, while, do-while. Today's two cousins: while and do-while. Same shape, one tiny difference.

while: condition first

#include <stdio.h>

int main() {
  int i = 1;
  while (i <= 5) {
    printf("%d ", i);
    i++;
  }
  printf("\n");
  return 0;
}

Output: 1 2 3 4 5.

Steps: 1. Check i <= 5. True → run body. 2. Body prints, increments. 3. Back to step 1. 4. When false (i = 6), exit.

If i started at 10, the body wouldn't run at all — while checks before executing.

do-while: condition last

int j = 10;
do {
  printf("%d ", j);
  j--;
} while (j >= 8);
printf("\n");

Output: 10 9 8.

Steps: 1. Run body. (Always — no check yet.) 2. Check j >= 8. True → loop again. 3. False → exit.

The body runs at least once, even if the condition is false from the start. Note the trailing semicolon after while (...) — required for do-while.

When to use which

while — "check first, may not run." - Reading lines from a file (might be empty). - Walking a linked list (might be NULL). - Polling a state until ready.

do-while — "always do once, then check." - Validating user input ("ask, then re-ask if bad"). - Game loops where you want at least one frame. - Random number generation that must produce some value.

In practice, while is far more common. do-while shows up mainly in input loops.

Input validation example

int x;
do {
  printf("Enter a number 1-10: ");
  scanf("%d", &x);
} while (x < 1 || x > 10);

Always prompt at least once. Re-prompt on invalid input. do-while reads naturally.

The while equivalent needs a sentinel:

int x = 0;   // sentinel
while (x < 1 || x > 10) {
  printf("Enter a number 1-10: ");
  scanf("%d", &x);
}

Slightly clunkier. do-while is the right tool here.

Avoiding infinite loops

The classic mistake:

int i = 1;
while (i <= 5) {
  printf("%d ", i);
  // forgot i++
}

i never changes; condition stays true; loop runs forever. Always make sure something inside the loop affects the condition.

When debugging an apparent infinite loop, inspect the condition variables. Add a print:

while (i <= 5) {
  printf("loop i=%d\n", i);
  // ...
}

If i never advances, you've found the bug.

break and continue

break exits the loop entirely:

int i = 0;
while (1) {
  if (i >= 5) break;
  printf("%d ", i);
  i++;
}
// Prints: 0 1 2 3 4

while (1) is an unconditional loop; break is the exit. Equivalent to while (i < 5), but useful when the exit condition is mid-body.

continue skips to the next iteration:

int i = 0;
while (i < 10) {
  i++;
  if (i % 2 == 0) continue;
  printf("%d ", i);
}
// Prints: 1 3 5 7 9 (only odds)

The continue jumps back to the condition check, skipping the rest of the body.

Nested loops

int i = 0;
while (i < 3) {
  int j = 0;
  while (j < 3) {
    printf("(%d,%d) ", i, j);
    j++;
  }
  i++;
}
printf("\n");
// (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)

break exits the innermost loop only. To exit multiple levels, use a flag or goto (uncommonly used; sometimes the right tool).

while (1) vs while (true)

C didn't have bool until C99 (<stdbool.h>). Older code uses while (1); modern C uses while (true):

#include <stdbool.h>
while (true) {
  // ...
  if (done) break;
}

Both compile to identical code. Use whichever your codebase prefers.

Counter loops are usually for

// Verbose with while
int i = 0;
while (i < 5) {
  printf("%d\n", i);
  i++;
}

// Cleaner with for (next episode)
for (int i = 0; i < 5; i++) {
  printf("%d\n", i);
}

When you have a counter that increments each iteration, for (next episode) is clearer.

Common mistakes

Forgetting to advance. Most common cause of infinite loops.

Wrong condition polarity. while continues while true; do-while's until would continue while false (in some other languages). C's do-while continues while true — same as while.

Missing semicolon after do-while. do { ... } while (cond) is a syntax error. Need do { ... } while (cond);.

Mutating the wrong variable. while (i <= 5) { j++; } — wrong variable advances; loop is infinite.

Off-by-one. while (i < 5) runs 5 times (i = 0 to 4). while (i <= 5) runs 6 times. Pick the right comparison.

What's next

Episode 8: for loops. When you have a counter, init + condition + step in one line.

Recap

while (cond) { ... } — check first, may not run. do { ... } while (cond); — always run once, check after. Trailing semicolon mandatory on do-while. break exits the loop; continue skips to next iteration. Always make sure the body affects the condition. For counter-style iteration, for (next episode) is cleaner.

Next episode: for loops.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.