Tino APCS

Nested Loops

To nest loops means to place one loop inside of another loop. The statement of the outer loop will be another inner loop. The following example will print a rectangular grid of stars with 4 rows and 8 columns.

for (int row = 1; row <= 4; row++){
  for (int col=1; col <= 8; col++){
    System.out.print("*");
  }
  System.out.println( );
}


Run Output:

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


For each occurrence of the outer row loop, the inner col loop will print 8 stars, terminated by the newline character.

The action of nested loops can be analyzed using a chart:

row col
1 1 to 8
2 1 to 8
3 1 to 8
4 1 to 8

Suppose we wanted to write a method that prints out the following 7-line pattern of stars:

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


Here is an analysis of the problem, line-by-line.

Line # # spaces # stars
1 0 7
2 1 6
3 2 5
...
7 6 1
L L - 1 N - L + 1

For a picture of N lines, each line L will have (L-1) spaces and (N-L+1) stars.

Here is a pseudocode version of the method.

A method to print a pattern of stars:

Print N lines of stars, each Line L consists of (L-1) spaces (N-L+1) stars a line feed

Here is the code version of the method.

void picture (int n){
  int line, spaces, stars, loop;

  for (line = 1; line <= n; line++){
    spaces = line - 1;
    for (loop = 1; loop <= spaces; loop++){
      System.out.print (" "); // print a blank space
    }
    stars = n - line + 1;
    for (loop = 1; loop <= stars; loop++){
      System.out.print ("*");
    }
    System.out.println();
  }
}


Dark Mode

Outline