C
Loops
A loop repeats a block of code while some condition holds — the tool for "do this 10 times," "keep reading until there's no more input," or "process every element in this array." C has three loop forms; this chapter is about picking the right one, not just knowing the syntax.
- What it is
- Three ways to repeat a block of code:
for,while, anddo-while. - Mental model
- All three ask the same question — "should I run this block again?" — they only differ in when that question gets asked and how the loop's own bookkeeping is written.
- Key numbers
- A
do-whilebody always runs at least once;forandwhilecan run zero times if the condition starts false. - Reach for it when
forwhen you know the number of iterations up front;whilewhen you don't;do-whilewhen the body must run at least once regardless.
for
A for loop bundles the three parts of "repeat N times" into one line: an initializer, a condition, and an update.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
// 0 1 2 3 4
while
A while loop checks its condition before every pass, including the first — if the condition starts false, the body never runs at all.
int count = 0;
while (count < 5) {
printf("%d\n", count);
count++;
}
// 0 1 2 3 4
This is the right shape whenever you don't know the number of iterations ahead of time — reading input until a sentinel value appears, or polling a hardware flag until it's set.
while (!data_ready()) {
// spin, waiting
}
process(read_data());
do-while
A do-while checks its condition after the body — guaranteeing the body runs at
least once, even if the condition is false from the start:
int choice;
do {
printf("Enter 1-5: ");
scanf("%d", &choice);
} while (choice < 1 || choice > 5);
This shape fits menus and input-validation loops exactly — you always need to ask at least once before you have anything to validate.
Which one to reach for
| Loop | Condition checked | Minimum runs | Best fit |
|---|---|---|---|
for | Before each pass | 0 | Known iteration count (array traversal, counting) |
while | Before each pass | 0 | Unknown iteration count (waiting, reading until done) |
do-while | After each pass | 1 | Body must run at least once (menus, input validation) |
break and continue
break- Exits the loop immediately, skipping every remaining iteration — execution resumes at the first statement after the loop.
continue- Skips the rest of the current iteration only and jumps straight to the next one's condition check — the loop itself keeps running.
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip printing 3, keep looping
if (i == 7) break; // stop the loop entirely at 7
printf("%d\n", i);
}
// 0 1 2 4 5 6
Real-world applications
- Array/buffer processing — a
forloop over a fixed-size array or ring buffer is the single most common loop shape in any C program. - Polling a hardware flag — a tight
whileloop waiting on a register bit or a "data ready" flag, common in bare-metal drivers before interrupts are involved. - The main firmware loop itself — most non-RTOS embedded firmware is structurally one giant
while (1) { ... }loop that never exits for the life of the device.
Gotchas
- An off-by-one error —
i <= 5instead ofi < 5— is the single most common loop bug in any language; it's worth deliberately double-checking the boundary condition every time you write one. - Modifying the loop variable inside the body of a
forloop (in addition to its own update clause) makes the iteration count very hard to reason about — usually a sign the loop should be restructured. - A
while (1) { ... }loop with nobreakanywhere inside is intentional in embedded firmware (the main loop is supposed to run forever) but is almost always a bug anywhere else. - Comparing a loop counter declared as
unsigned intagainst0with>=in a countdown loop (for (unsigned int i = 10; i >= 0; i--)) never terminates — an unsigned value can never go below0, it wraps around to a huge positive number instead.