For Loops: Repeat a Known Number of Times
Label the boxes with a loop
A conditional chooses whether to do some work. A loop repeats work while a condition stays true. Each pass through its body is called an iteration.
Three boxes need numbered labels. A for loop keeps the starting number, condition, and update together:
#include <stdio.h>
int main(void) {
for (int box = 1; box <= 3; box++) {
printf("Box %d\n", box);
}
printf("All boxes labeled\n");
return 0;
}
Read for (int box = 1; box <= 3; box++) in three parts. The first initializes box once. The second is tested before every pass. The third runs after each completed body; here box++ adds one, like box = box + 1;. The two semicolons separate those parts. Do not add a semicolon after the closing parenthesis: the following braced block is the body.
| Value at the test | box <= 3 | Work performed | Value after update |
|---|---|---|---|
| 1 | True | Print Box 1 | 2 |
| 2 | True | Print Box 2 | 3 |
| 3 | True | Print Box 3 | 4 |
| 4 | False | Leave the loop | No update |
Run it. The final message is outside the loop, so it prints once after all three labels. A loop whose condition never becomes false can keep running indefinitely; its update must make progress toward stopping.
Keep a running total
#include <stdio.h>
int main(void) {
int sum = 0;
for (int number = 1; number <= 4; number++) {
sum = sum + number;
}
printf("Sum: %d\n", sum);
return 0;
}
An accumulator is a variable that keeps a running result. sum starts at zero outside the loop, so each pass adds to the result left by the previous pass. Initializing it inside the body would discard that earlier work on every iteration.
Run the total and check for 10. The print comes after the loop because we want one final total, not all the intermediate totals.
Starting at 1 and using <= 3 visits 1, 2, 3. Starting at 0 and using < 3 visits 0, 1, 2. Both give three passes, but different values. Choose the range your task needs.