2.11 Nested iterationLoops inside loops

A nested loop is a loop inside the body of another loop. For every single pass of the outer loop, the inner loop starts over and runs all of its passes. Only when the inner loop finishes does the outer loop move to its next pass. Nested loops are how you handle anything with two dimensions: rows and columns, every pair of items, or every starting point and every length.
1for (int row = 1; row <= 4; row++)12{3 for (int col = 1; col <= row; col++)24 {5 System.out.print(col);6 }37 System.out.println();8}
- line 1 Outer loop: one pass per row
- line 3 Inner loop restarts at 1 on every row
- line 6 After the inner loop ends: next line
?Wait, what's the difference between print and println again?
| row | col takes | inner passes | line printed |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 1, 2 | 2 | 12 |
| 3 | 1, 2, 3 | 3 | 123 |
| 4 | 1, 2, 3, 4 | 4 | 1234 |
| total | 10 |
To trace a nested loop, write the outer variable on the left and, for each of its values, list every value the inner variable takes. Watch for inner loops whose start or end depends on the outer variable, like col <= row or j = i. Those change from row to row.
?Wait, why does the inner loop restart at 1 each row?
I thought about it. Show me
What is printed?
int total = 0;
for (int i = 1; i <= 3; i++)
{
for (int j = i; j <= 3; j++)
{
total += i * j;
}
}
System.out.println(total);- The inner loop starts at j = i, so it gets shorter each time. List the pairs row by row.
Why?
An inner bound that depends on the outer variable is the thing to watch in every nested loop question. - i = 1: j is 1, 2, 3. Products 1, 2, 3, which add 6. total is 6.
- i = 2: j is 2, 3. Products 4 and 6, which add 10. total is 16.
- i = 3: j is 3 only. Product 9. total is 25. Then i becomes 4, 4 <= 3 is false, and the outer loop ends.
Answer: 25
Stuck? Get a hint
- Make a row for each value of i, and list the j values in that row.
- j starts at i, not at 1.
- Add i * j for every pair: 6, then 10, then 9.
for (int r = 1; r <= 4; r++)
{
for (int c = 1; c < r; c++)
{
System.out.print("*");
}
}- A8
- B6
- C12
- D9
Show the answer
B. The inner loop runs while c < r. For r = 1 it runs 0 times, r = 2 once, r = 3 twice, r = 4 three times: 0 + 1 + 2 + 3 = 6. Choice C multiplies 4 × 3 as if both bounds were fixed, but the inner bound depends on r.
- The inner loop runs all its passes for every single pass of the outer loop.
- Trace one outer value at a time, listing every inner value.
- Watch inner bounds that use the outer variable (j = i, col <= row).
- print inside the inner loop, println after it: one line per outer pass.