Skip to main content
ICT
Lesson A12 - Iterations
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

E. Nested Loops page 7 of 18

  1. To nest loops means to place one loop inside of another loop. The statement of the outer loop will be another inner loop.
  1. 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:

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

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

  2. 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

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

  4. *******
     ******
      *****
       ****
        ***
         **
          *

  5. 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.

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

  7. 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();
      }
    }

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.