TOPIC 2.11 · STUDY
Nested Iteration
Nested iteration places one loop inside another. The inner loop runs to completion on every pass of the outer loop. A while counter used for the inner loop must be reset inside the outer body; a for loop's initialization does that reset when the for sits inside the outer loop.
2.11.A
Nested Iteration
Nested iteration means one loop sits inside the body of another. Call the outer loop the one that encloses the other, and the inner loop the one inside. On each pass of the outer loop, the inner loop starts, runs until its own condition fails, and finishes before the outer loop moves on to its next pass.
Count the total runs of the inner body by multiplying. If the outer loop runs 3 times and the inner loop runs 2 times on every outer pass, the inner body runs 3 x 2 = 6 times.
for (int round = 1; round <= 3; round++) {
for (int tick = 1; tick <= 2; tick++) {
System.out.print(".");
}
}
// Outer: 3 passes. Inner: 2 prints each pass. Output: ......
Each outer pass can reprint the same inner sequence. Two outer passes that each print 1 then 2 then 3 produce 123123 on one line, not 123 once.
int lap = 1;
while (lap <= 2) {
int n = 1;
while (n <= 3) {
System.out.print(n);
n++;
}
lap++;
}
// Each lap resets n to 1, so both passes print 123. Output: 123123
Each outer pass waits for the full inner sequence. The second pass repeats the same 1 2 3 after the first pass finishes.
When the inner loop is a while that uses a counter, that counter must be reset inside the outer loop before the inner while starts. Otherwise the counter keeps the value left from the previous outer pass, and the inner condition may already be false.
A for loop declared inside the outer body resets itself through its initialization. Each time the outer loop reaches that for, the for header runs again and sets the inner counter back to its starting value.
for (int lap = 1; lap <= 2; lap++) {
for (int n = 1; n <= 3; n++) {
System.out.print(n);
}
}
// The for header resets n to 1 on every lap. Output: 123123
Key points
- An inner loop runs to completion on every pass of the outer loop.
- Outer passes times inner passes equals how many times the inner body runs.
- Each outer pass can reprint the same inner sequence.
- Reset an inner while counter inside the outer loop before the inner while starts.
- A for loop's initialization resets the inner counter when that for sits inside the outer body.
Forgetting to reset an inner while counter makes later outer passes skip the inner body.