next up previous
Next: Example: power by means Up: Unit 06 Previous: Nested loops

Example of nested loop: print out a pyramid of stars

In the previous example, where we printed out the multiplication table, the number of iterations of the internal loop was fixed. In general, the number of iterations of an internal loop may depend on the iteration of the external loop.

Example: Print out a pyramid of stars.

Pyramid of height 4      row  blanks    *
   *                      1      3      1
  ***                     2      2      3
 *****                    3      1      5
*******                   4      0      7

To print the generic row r: print (height - r) blanks and (2 . r - 1) stars.

int height;
height = Integer.parseInt(JOptionPane.showInputDialog("Input the height"));

for (int row = 1; row <= height; row++) {
                      // 1 iteration for each row of the pyramid
  for (int i = 1; i <= height - row; i++)
    System.out.print(" ");    // prints the initial blanks

  for (int i = 1; i <= row * 2 - 1; i++)
    System.out.print("*");    // prints the sequence of stars

  System.out.println();       // prints a newline: the row is finished
}


next up previous
Next: Example: power by means Up: Unit 06 Previous: Nested loops