ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.11

Nested Iteration

Skill 2.ASkill 3.DSkill 4.B

Big idea: With a loop inside a loop, the inner loop runs all the way through for every single pass of the outer loop.

Learning objectives
  • Develop code to represent nested iterative processes and determine the result of these processes.

Rows and columns

Think of the outer loop as rows and the inner loop as columns. The inner loop's variable resets each time the outer loop starts a new pass.

Code
for (int r = 1; r <= 3; r++) {
  for (int c = 1; c <= 4; c++) {
    System.out.print(r * c + " ");
  }
  System.out.println();
}
Output
1 2 3 4
2 4 6 8
3 6 9 12

Triangles: inner bound depends on outer

Code
for (int r = 1; r <= 4; r++) {
  for (int c = 1; c <= r; c++) {
    System.out.print("*");
  }
  System.out.println();
}
Output
*
**
***
****

Comparing every pair

Starting the inner loop at i + 1 visits each pair once, without comparing an item to itself.

Code
String s = "abcb";
boolean dup = false;
for (int i = 0; i < s.length(); i++) {
  for (int j = i + 1; j < s.length(); j++) {
    if (s.substring(i, i + 1).equals(s.substring(j, j + 1))) dup = true;
  }
}
System.out.println(dup);
Output
true
Key points
  • A nested loop is a loop inside another loop's body.
  • The inner loop completes all its iterations for each iteration of the outer loop.
Watch out
  • Use different variable names for the inner and outer loops.
  • Check where println() sits: inside the inner loop, it prints every element on its own line.
Quick check
How many stars?
for (int i = 0; i < 3; i++)
  for (int j = 0; j < 5; j++)
    System.out.print("*");
Show answer
15 (3 × 5).