Nested Loop - Java Sample Program

for (i = 0; i <= 3; i++) //Line 1
{ //Line 2
for (j = 0; j <= i; j++) //Line 3
System.out.print("*"); //Line 4
System.out.println(); //Line 5
} //Line 6

These lines of code produce the following output:
*
**
***
****
The output consists of four rows of stars rather than three rows of stars, as intended
originally.

***********************************************************************************
for (i = 1; i <= 5; i++) //Line 1
{ //Line 2
for (j = 1; j <= 10; j++) //Line 3
System.out.printf("%3d", i * j); //Line 4
System.out.println(); //Line 5
}

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50

The multiplication table has five lines. Therefore, as in Example 5-18, we use a for
statement to output these lines as follows:

No comments: