Java Reference
In-Depth Information
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 4.7 presents a program that uses nested
for
loops to display a multiplication table.
nested loop
L
ISTING
4.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
table title
// Display table body
outer loop
15
16 System.out.print(i +
" | "
);
17
18 /
/ Display the product and align properly
19 System.out.printf(
"%4d"
,
i * j);
20 }
21 System.out.println();
22 }
23 }
24 }
for
(
int
i =
1
;
i <=
9
;
i++) {
inner loop
for
(
int
j =
1
;
j <=
9
;
j++) {
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
The program displays a title (line 5) on the first line in the output. The first
for
loop (lines
9-10) displays the numbers
1
through
9
on the second line. A dashed (
-
) line is displayed on
the third line (line 12).
The next loop (lines 15-22) 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
.