Loops
while, do-while, and for — how to make programs repeat
A loop runs the same block of code over and over until some condition tells it to stop. Combined with conditionals, loops give you all the expressive power you need to do anything a computer can do. (That's a theorem, actually — the structured programming theorem — but you don't have to take a class to feel it.)
C has three loop forms. They differ in style; the substance is the same.
The while loop
while (condition) {
// body
}Check the condition. If true, run the body. Repeat. Stop when the condition becomes false.
Trace it:
| iteration | i (before) | condition | i (after body) |
|---|---|---|---|
| 1 | 1 | 1 ≤ 5 = true | 2 |
| 2 | 2 | 2 ≤ 5 = true | 3 |
| 3 | 3 | 3 ≤ 5 = true | 4 |
| 4 | 4 | 4 ≤ 5 = true | 5 |
| 5 | 5 | 5 ≤ 5 = true | 6 |
| 6 | 6 | 6 ≤ 5 = false | — exit |
If you forget to update i, the loop runs forever. This is the
beginner's nightmare:
int i = 1;
while (i <= 5) {
printf("i = %d\n", i);
// forgot: i = i + 1;
}In the browser sandbox, the program will eventually time out. On your laptop, you would have to kill the process by hand. Always ensure that something inside the loop changes the condition.
The for loop
for is while with three slots baked into one line: an
initialization, a condition, and an increment.
for (init; condition; increment) {
// body
}It is exactly equivalent to:
init;
while (condition) {
// body
increment;
}The two snippets below print the same thing:
i++ is shorthand for i = i + 1. Likewise i-- for i = i - 1,
and i += 3 for i = i + 3.
for is the natural choice when you know in advance how many times
to loop or you are stepping through a known range. The
initialization, the stop condition, and the step are all visible on a
single line, which makes the loop easy to read.
The do-while loop
do {
// body
} while (condition);Like while, but the condition is checked after the body. The
body always runs at least once. This is handy for input loops where
you must ask first and check the answer second.
Loops + conditionals: a real example
Let's print every even number from 1 to 20:
There are two ways to think about this:
- "Walk through every number from 1 to 20. Print the even ones."
- "Walk through every even number from 2 to 20."
The second is more efficient (half the iterations). Try rewriting:
for (int i = 2; i <= 20; i += 2) {
printf("%d ", i);
}Both produce identical output. As you get more comfortable, look for ways to express the intent directly in the loop header.
break and continue
Sometimes you want to exit a loop early or skip to the next iteration.
breakexits the innermost enclosing loop immediately.continuejumps straight to the next iteration's condition check.
Expected output: 1 2 4 5 7 8.
Nested loops
You can put a loop inside a loop. The inner loop runs in full for every iteration of the outer loop.
Nested loops are how you walk a 2D grid: rows and columns, x and y, month and day.
Counting up vs counting down
You can run a loop backwards. It's the same idea, just flipped:
A classic countdown.
Flowchart view
Every loop, no matter the syntax, has this same shape: init, condition, body, update, back to condition.
Challenge: factorial
Compute N! (N factorial — the product of all integers from 1 to N) for N = 6 and print the result followed by a newline. The expected output is 720.
Challenge: triangle of stars
Print a right triangle of * characters with 5 rows. Row i should have i stars, separated by nothing. The expected output is exactly:
*
**
***
****
*****
How many times does the body of this loop run?
for (int i = 0; i < 10; i += 2) {
// body
}
10
5
6
Infinite — the loop never stops.
Which of the following describes the difference between break and continue?
break exits the loop entirely; continue skips to the next iteration's condition check.
break skips the next iteration; continue exits the loop.
They behave identically.
break works only in switch; continue works only in loops.