4.6 Nesting Loop Structures

In using a loop, the body can contain any valid Java statements, including other loop statements. Thus we can have while, do, and for statements within other while, do, and for statements. If a first loop contains a second loop, we say that the second is nested within the first. The first loop is referred to as the outer loop and the second as the inner loop.

To take a simple example, suppose that we want to print a triangular pattern of asterisks, like the one shown below.

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

The statement System.out.print("*"); will print one asterisk. To print a complete line of asterisks, we can use a loop containing this statement, with the loop followed by the statement System.out.println(); to end the line. To print a number of such lines, we can use another loop containing the instructions for writing one line. The result is shown in the next example.

Example 1

The following fragment prints a triangle of asterisks with the size of the triangle determined by the value of numberOfRows.
  for (row = 1; row <= numberOfRows; row++)
  {
    for (position = 1; position <= row; position++)
      System.out.print("*");
    System.out.println();
  } 

As we have already noted, loop nesting is not limited to for statements. We can nest any form of loop inside any other form, as illustrated in the next example.

Example 2

Suppose that we want to write a program that repeatedly prompts a user to provide integer values (until the user provides a value of zero). For each non-zero value read, the program prints the number and the sum of its digits. We can begin to attack the problem by constructing code to handle one value. Our strategy is to first eliminate any negative sign from the number and then strip off the final digits, one by one, and add them up. This continues until there are no more digits to strip off. A while loop handles this nicely. In the fragment, n is the value whose digits are to be added.

  int absN = Math.abs(n);
  int digitSum = 0;
  while (absN > 0)
  {
    digitSum += absN % 10; // add last digit to digit sum 
    absN /= 10; // and strip it off the number
  }
  System.out.println("Sum of digits of "+n+" is "+digitSum);

Having solved the problem for one value of n, we can then embed this into a loop that keeps prompting and reading until the user supplies a value of zero. We have chosen to use a do statement for this loop. Here is the final program.

  class DigitAddition
  {
    public static void main (String[] args)
    {
      int n;
      do 
      {
        System.out.println("Give an integer (0 to stop)");
        n = In.getInt();
        if (n != 0)
        {
          int absN = Math.abs(n);
          int digitSum = 0;
          while (absN > 0)
          { 
            digitSum += absN % 10; // add last digit
            absN /= 10; // and delete it
          }
          System.out.println("Sum of digits of " + n + " is " + digitSum);
        }
      }
      while (n != 0);
    }
  }

Exercise 4.6

  1. Assuming that SIZE has the value 5, determine the output that will be produced by the following fragment.
      for (i = 1; i <= SIZE; i++)
      {
        for (j = SIZE; j >= i; j--)
          System.out.print("*");
        System.out.println();
      }
    
  2. Write a program that will print a triangular pattern of asterisks whose maximum width is determined by input from the user. The diagram shows the pattern that should be printed if the user's input is 5.


  3. Write a program using nested loops that prints the following pattern.


  4. Write a program using nested loops that prints the following pattern.


  5. Three positive integers a, b, and c with a < b < c form a Pythagorean triplet if a2 + b2 = c2 . For example, 3, 4, and 5 form a Pythagorean triplet since 32 + 42 = 52. Write a program that first prompts the user for a positive integer and then finds and prints all Pythagorean triplets whose largest member is less than or equal to that integer.

  6. Write a program that will first prompt the user for the height and width of a pattern and will then print a pattern that is the given number of lines high and the given number of characters wide. The pattern should contain stars and blanks similar to the pattern shown in the flag of the United States. For example, if the user specified a height of 5 and a width of 11, the program should produce the following output. Assume that the user provides valid input.


  7. Write a program that first prompts the user (repeatedly, if necessary) to supply a single digit (0,1,2, ... ,9). The program should then repeatedly prompt the user to supply integer values until the user provides a value of zero which acts as a sentinel to terminate the program. For each integer read (except for the final zero), the program should count the number of occurrences of the digit read in the first part of the program and should print this count.