Label a Two-Row Shelf
Label two rows of shelves
Each of two shelf rows has three positions. A nested loop is a loop inside another loop. Here the outer loop selects a row, and the inner loop labels all its positions before the row changes.
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 2; row++) {
for (int position = 1; position <= 3; position++) {
printf("R%d-P%d\n", row, position);
}
}
return 0;
}
Trace the pair (row, position) in output order:
| Outer pass | Inner values | Labels |
|---|---|---|
row = 1 | 1, 2, 3 | R1-P1, R1-P2, R1-P3 |
row = 2 | 1, 2, 3 again | R2-P1, R2-P2, R2-P3 |
The declaration int position = 1 runs each time the outer body reaches the inner loop. That is why positions restart at 1 for row 2. The outer row does not advance after every printed label; it waits for the entire inner loop to finish.
Run the example and check the six lines. Changing the outer limit to 3 would add a full third row of three labels.
Leaving or skipping a pass
You saw break leave a switch. Inside a loop, break leaves the nearest enclosing loop. In this example, a break inside the inner loop would end that row's positions, not the outer row loop.
continue skips the rest of the current loop body. In a for, execution then reaches the update and the next test; in a while, it returns to the test, so it can skip an update placed later in the body. You do not need either statement for the next exercise. Complete all the drawers in each bay before moving on.