Nested Loops

In this lesson, we will look at nesting a loop within the body of another one.

Problem statement

Imagine that we want to display a square pattern of stars (asterisks), such as:

* * * *
* * * *
* * * *
* * * *

where the number of rows and the number of stars per row are the same. This number is essentially the length of the side of the square. However, we might not know this length in advance. If we ask the user for this value—call it n—we need a loop to display n stars in one row. We need either n such loops—impossible since the value of n can change—or we need to execute one loop n times. That is, our loop needs to be within the body of another loop. Such loops are called nested loops.

A pseudocode solution

The following logic is a first attempt at solving our problem:

while (another row must be displayed)
{
   while (another star must be displayed in this row)
      Display a star

   Go to a new line
}

The inner loop displays all the stars that are in one row. It executes once for each row. That is, each time the outer loop cycles, the inner loop executes completely, displaying n stars. The last step in the outer loop then begins a new line.

After asking the user for n, the length of the side of the square, we can control each of the loops by counting. Thus, we can refine the previous logic as follows:

sideLength = value entered by user
rowCounter = 1
while (rowCounter <= sideLength)
{
   starCounter = 1
   while (starCounter <= sideLength)
   {
      Display a star
      Add 1 to starCounter
   }
   Go to a new line
   Add 1 to rowCounter
}

The outer loop cycles sideLength times, since rowCounter counts from 1 to sideLength. For each of those cycles, the inner loop cycles sideLength times, since starCounter counts from 1 to sideLength. Thus, the inner loop displays sideLength stars in a row for each cycle of the outer loop, producing sideLength rows of sideLength stars.

The Java program

The following Java program implements this logic:

Get hands-on with 1400+ tech skills courses.