Friday, November 18, 2011

Java (Nested Loops)


Nested Loops

Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew.
Listing 4.4 presents a program that uses nested for loops to print a multiplication table, as shown in Figure 4.6.


Figure 4.6. The program uses nested for loops to print a multiplication table.



Listing 4.4. MultiplicationTable.java

 1 import javax.swing.JOptionPane;
 2
 3 public class MultiplicationTable {
 4    /** Main method */
 5    public static void main(String[] args) {
 6      // Display the table heading
 7      String output = "                Multiplication Table\n";
 8      output += "------------------------------------------------\n";
 9
10      // Display the number title
11      output += " | ";
12      for (int j = 1; j <= 9; j++)
13        output += " " + j;
14
15      output += "\n";
16
17      // Print table body
18      for (int i = 1; i <= 9; i++) {
19        output += i + " | ";
20        for (int j = 1 j < = 9; j++) {
21          // Display the product and align properly
22          if (i * j < 10)
23            output += " " + i * j;
24          else
25            output += " " + i * j;
26        }
27        output += "\n";
28      }
29
30      // Display result
31      JOptionPane.showMessageDialog(null, output);
32    }
33  }
The program displays a title (line 7) on the first line and dashes (-) (line 8) on the second line. The first for loop (lines 12–13) displays the numbers 1 through 9 on the third line.
The next loop (lines 18–28) is a nested for loop with the control variable i in the outer loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner loop, with j being 1, 2, 3, …, 9. The if statement in the inner loop (lines 22–25) is used so that the product will be aligned properly. If the product is a single digit, it is displayed with an extra space before it.

No comments:

Post a Comment