Incremental Java
Nested Loops

Nested Loops

A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too.

Example: Printing a Grid of Stars

You're asked to implement the following method:
public void printRect() ;
This prints a rectangular grid of stars with width columns and height rows.

This is a problem that can be solved using nested loops. Let's think about how to solve this.

First, you need to know that Java prints like a typewriter. It prints row by row. Once a row has been printed, it can't go back up. This is not like a two-dimensional screen, where you can write at (x,y) locations whereever you feel like.

One idea is to think of a single loop, then figure out how to do the other loop. It's usually easier to start out with the outer loop first.

Here's a start:

public void printGrid()
{
   for ( int i = 0 ; i < height ; i++ )
   {
     // PRINT a row
   }
}
This basic loop iterates over each row. There are height of these rows. For each row, we want to print width stars.

But we've already written code to do that! It looks like:

   for ( int i = 0 ; i < width ; i++ )
   {
      System.out.print( "*" ) ;
   }
   // PRINT newline
   System.out.println( "" ) ;
Let's copy these 5 lines of code (2 are braces) under the comment PRINT a row.
public void printGrid()
{
   for ( int i = 0 ; i < height ; i++ )
   {
      // PRINT a row
      for ( int i = 0 ; i < width ; i++ )
      {
         System.out.print( "*" ) ;
      }
      // PRINT newline
      System.out.println( "" ) ;
   }
}
There is a small problem. We've used i in both locations. This doesn't even compile! Even if it did, it would do the wrong thing.

The solution is to change the looping variables so the inner loop's looping variable isn't the same as the outer loop's looping variable. Just to make it easier to read, we'll name the outer looping variable, row, and the inner looping variable, col.

public void printGrid()
{
   for ( int row = 0 ; row < height ; row++ )
   {
      // PRINT a row
      for ( int col = 0 ; col < width ; col++ )
      {
         System.out.print( "*" ) ;
      }
      // PRINT newline
      System.out.println( "" ) ;
   }
}
Recall that width and height are instance variables.

Trace It Out!

Try an example where width is 3 and height is 2, and see if it does what you expect.

Variations on a Theme

You can triply nest loop (a loop within a loop within a loop) or have an if statement in a loop or a loop in an if statement.

You can also write one loop. Then, you can write another loop!

With practice reading and writing code, you'll get a feel for when you need to do what.