C Basics · beginner · ~10 min

for / while / do-while

Pick the right loop shape for the job.

Overview

Loops execute a block of code repeatedly. C has three flavours: while (test, run, repeat), do/while (run once, then test), and for (set up, test, advance — best for counting). All three can be exited early with break and skipped to the next iteration with continue.

Why it matters

Iteration is what makes computers useful. Without loops, summing a million numbers would require a million lines of code. With them, you write three lines that work for any input size. Every search, every render, every network read is a loop somewhere underneath.

Core concepts

Loop invariant. A statement that's true before each iteration. Naming yours (// invariant: sum holds the total of a[0..i-1]) is the easiest way to catch off-by-one bugs. Bounded vs unbounded. Counting loops have a known upper bound (for (i=0; i<n; i++)); event loops are unbounded (while (1) until something tells you to stop). Pre- vs post-test. while checks before the body; do/while runs the body first, then checks — useful when the loop must execute at least once (input prompts, retry loops).

Syntax notes

while (cond) { /* body */ }
do { /* body */ } while (cond);
for (init; cond; step) { /* body */ }

Any of init, cond, step can be empty: for (;;) is the canonical infinite loop. break exits the innermost loop; continue jumps to the test (or to step in a for-loop).

Lesson

C has three loop forms:

  • for (init; cond; step) — use when the iteration count is bounded or you have a clear loop variable.
  • while (cond) — use when the termination condition is in the middle.
  • do { ... } while (cond) — use when the body must run at least once.

break exits the innermost loop, continue skips to the next iteration.

Code examples

for (size_t i = 0; i < n; i++) {
    if (a[i] < 0) continue;     // skip negatives
    if (a[i] > 100) break;      // stop entirely
    sum += a[i];
}

Common mistakes

  • Off-by-one: use < with the array length, not <=.
  • Infinite loop because the step is wrong direction or never executes.

Debugging tips

If a loop runs once when you expected it not to (or never when you expected it to), print the condition and the loop variable on the first iteration. Off-by-one bugs almost always hide in the < vs <= choice on the upper bound. Infinite loops? Add printf("i=%d\n", i); to confirm the variable is advancing.

Memory safety

Loops over arrays are a top source of out-of-bounds writes. The pattern for (i=0; i<n; i++) a[i] = ... is safe; for (i=0; i<=n; i++) overruns by one. Always pair the bound with the array length, not a free-floating constant.

Real-world uses

Iterating over arrays, processing each line of a file, polling a hardware register until a bit changes, the main loop of a game, an HTTP server's accept loop, every state-machine driver in a kernel.

Practice tasks

  1. Sum the first 100 integers using each of the three loop forms. 2. Print the multiplication table from 1×1 to 9×9 using nested for-loops. 3. Read characters until EOF and count vowels. 4. Use break to stop at the first negative number in an array.

Summary

Loops compress repetition into a few lines. Match the loop form to the situation (for to count, while to wait, do/while to ensure-at-least-once), name the invariant, and watch the boundary conditions — that's where 90% of off-by-one bugs live.

Practice with these exercises