Java Reference
In-Depth Information
5.18
What is wrong with the following programs?
1 public class ShowErrors {
2 public static void main(String[] args) {
3 int i = 0 ;
4 do {
5 System.out.println(i + 4 );
6 i++;
7 }
8
1 public class ShowErrors {
2 public static void main(String[] args) {
3 for ( int i = 0 ; i < 10 ; i++);
4 System.out.println(i + 4 );
5 }
6 }
while (i < 10 )
9 }
10 }
(a)
(b)
5.6 Nested Loops
A loop can be nested inside another loop.
Key
Point
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 5.7 presents a program that uses nested for loops to display a multiplication table.
nested loop
L ISTING 5.7
MultiplicationTable.java
1 public class MultiplicationTable {
2 /** Main method */
3 public static void main(String[] args) {
4 // Display the table heading
5 System.out.println( " Multiplication Table" );
6
7 // Display the number title
8 System.out.print( " " );
9 for ( int j = 1 ; j <= 9 ; j++)
10 System.out.print( " " + j);
11
12 System.out.println( "\n———————————————————————————————————————" );
13
14 // Display table body
15 for ( int i = 1 ; i <= 9 ; i++) {
16 System.out.print(i + " | " );
17 for ( int j = 1 ; j <= 9 ; j++) {
18 / / Display the product and align properly
19 System.out.printf( "%4d" , i * j);
20 }
21 System.out.println();
22 }
23 }
24 }
table title
outer loop
inner loop
Multiplication Table
1 2 3 4 5 6 7 8 9
———————————————————————————————————————-
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81
 
 
 
Search WWH ::




Custom Search