Skip to main content
Lesson 10 - for, do-while, Nested Loops
Lesson MenuPreviousNext
  
Nested Loops page 4 of 10

  1. To nest a loop means to place one loop inside another loop. The statement of the outer loop will consist of another inner loop.

  2. The following example will print a rectangular grid of stars with 4 rows and 8 columns.

    for (int row = 1;  row <= 4;  row++)
    {
      for (col=1;  col <= 8;  col++)
        System.out.print("*");
      System.out.println( );
    }
    
    Output:
    
    ********
    ********
    ********
    ********
  3. For each occurrence of the outer row loop, the inner col loop will print its 8 stars, terminated by the newline character.

  4. 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
  5. Suppose we wanted to write a method that prints out the following 7-line pattern of stars:

    *******
     ******
      *****
       ****
        ***
         **
          *
  6. 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.

  7. 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
  8. 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.println ("*");
        System.out.println ( );
      }
    }

Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.