|
|
|
DEMO: demo/05-loops/06-nested-loop/Demo1.java Step the program in BlueJ
Write a Java program that prints the multiplication table for the number 1 to 9
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
|
Code:
|
|
The program will print 1 line of the table in each outer iteration:
i = 1 1 2 3 4 5 6 7 8 9 <--- print this line in iter 1 i = 2 2 4 6 8 10 12 14 16 18 <--- print this line in iter 2 i = 3 3 6 9 12 15 18 21 24 27 <--- print this line in iter 3 i = 4 4 8 12 16 20 24 28 32 36 <--- print this line in iter 4 i = 5 5 10 15 20 25 30 35 40 45 <--- print this line in iter 5 i = 6 6 12 18 24 30 36 42 48 54 <--- print this line in iter 6 i = 7 7 14 21 28 35 42 49 56 63 <--- print this line in iter 7 i = 8 8 16 24 32 40 48 56 64 72 <--- print this line in iter 8 i = 9 9 18 27 36 45 54 63 72 81 <--- print this line in iter 9 |
Code:
for ( i = 1; i <= 9; i++ ) // Program will repeat for i = 1, 2, 3, ... 9
{
// print line i
}
|
The numbers on line i are equal to: 1*i 2*i 3*i 4*i 5*i 6*i 7*i 8*i 9*i:
i = 1 1 2 3 4 5 6 7 8 9 <--- print this line in iter 1
i = 2 2 4 6 8 10 12 14 16 18 <--- print this line in iter 2
i = 3 3 6 9 12 15 18 21 24 27 <--- print this line in iter 3
i = 4 4 8 12 16 20 24 28 32 36 <--- print this line in iter 4
i = 5 5 10 15 20 25 30 35 40 45 <--- print this line in iter 5
i = 6 6 12 18 24 30 36 42 48 54 <--- print this line in iter 6
i = 7 7 14 21 28 35 42 49 56 63 <--- print this line in iter 7
i = 8 8 16 24 32 40 48 56 64 72 <--- print this line in iter 8
i = 9 9 18 27 36 45 54 63 72 81 <--- print this line in iter 9
|
Code:
for ( i = 1; i <= 9; i++ ) // Program will repeat for i = 1, 2, 3, ... 9
{
for ( j = 1; j <= 9; j++ )
System.out.print(" " + j*i); // prints 1*i 2*i 3*i ... 9*i
System.out.println(); // prints "empty line" (go to next line)
}
|
DEMO: demo/05-loops/06-nested-loop/MultTable.java
The complete Java program is:
public static void main(String[] args)
{
int i, j;
for ( i = 1; i <= 9; i++ )
{
for ( j = 1; j <= 9; j++ )
System.out.print(" " + i*j);
System.out.println();
}
}
|
Improvement: use System.out.printf("%4d", i*j) to print i*j in 4 characters places:
for ( i = 1; i <= 9; i++ ) // Program will repeat for i = 1, 2, 3, ... 9
{
for ( j = 1; j <= 9; j++ )
System.out.printf("%4d" , i*j); // prints 1*i 2*i 3*i ... 9*i
System.out.println(); // prints "empty line" (go to next line)
}
|
DEMO: demo/05-loops/06-nested-loop/MultTable2.java