C Basics · beginner · ~10 min
Pick the right loop shape for the job.
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.
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.
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).
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).
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.
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];
}
< with the array length, not <=.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.
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.
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.
break to stop at the first negative number in an array.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.