7.4. Nested For LoopsΒΆ

A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below.

Note

The number of times a nested for loop body is executed is the number of times the outer loop executes times the number of times the inner loop executes. For the example above the outer loop executes 4-0+1= 5 times and the inner 9-0+1=10 times so the total is 5 * 10 = 50.

Check your understanding

    6-4-1: How many times does the following code print a *?

    for (int i = 3; i < 8; i++)
    {
        for (int y = 1; y < 5; y++)
        {
            System.out.print("*");
        }
        System.out.println();
    }
    
  • 40
  • This would be true if the outer loop executed 8 times and the inner 5 times, but what is the initial value of i?
  • 20
  • The outer loop executes 7-3+1=5 times and the inner 4-1+1=4 so this will print 5 * 4 = 20 stars.
  • 24
  • This would be true if the outer loop executed 6 times such as if it was i <= 8.
  • 30
  • This would be true if the inner loop executed 5 times such as if it was y <= 5.

    6-4-2: What does the following code print?

    for (int i = 2; i < 8; i++)
    {
        for (int y = 1; y <= 5; y++)
        {
            System.out.print("*");
        }
        System.out.println();
    }
    
  • A rectangle of 8 rows with 5 stars per row.
  • This would be true if i was initialized to 0.
  • A rectangle of 8 rows with 4 stars per row.
  • This would be true if i was initialized to 0 and the inner loop continued while y < 5.
  • A rectangle of 6 rows with 5 stars per row.
  • The outer loop executes 8-2+1=6 times so there are 6 rows and the inner loop executes 5-1+1=5 times so there are 5 columns.
  • A rectangle of 6 rows with 4 stars per row.
  • This would be true if the inner loop continued while y < 5.

    6-4-3: What does the following print?

    for (int i = 3; i <= 9; i++)
    {
       for (int j = 6; j > 0; j--)
       {
           System.out.print("*");
       }
       System.out.println();
    }
    
  • A rectangle of 9 rows and 5 stars per row.
  • Did you notice what i was initialized to?
  • A rectangle of 6 rows and 6 stars per row.
  • It would print 6 rows if it was i < 9.
  • A rectangle of 7 rows and 5 stars per row.
  • It would print 5 stars per row if it was j > 1.
  • A rectangle of 7 rows and 6 stars per row.
  • The outer loop executes 9 - 3 + 1 = 7 times and the inner 6 - 1 + 1 = 6 times.
Next Section - 7.5. Common Mistakes