Java Reference
In-Depth Information
The condition expression for the inner for -loop statement ( j <= 3) is evaluated for j
equal to 4, which is false. At this point, the inner for loop is finished.
14.
The last statement of the block statement for outer for -loop statement, which is
System.out.println(), is executed, which prints a system-dependent line separator.
15.
The expression-list of the outer for -loop statement (i++) is executed, which increment
the value if i to 2 .
16.
Now, the inner for -loop statement is started afresh with the value of i equal to 2. This
sequence of steps is also executed for i equal to 3. When i becomes 4, the outer for -loop
statement exits, and at this point, the printed matrix will be
11 12 13
21 22 23
31 32 33
17.
Note that this snippet of code also prints a tab character at the end of every row and a new line after the last row,
which are not necessary. One important point to note is that the variable j is created every time the inner for -loop
statement is started and it is destroyed when the inner for -loop statement exits. Therefore, the variable j is created and
destroyed three times. You cannot use the variable j outside the inner for -loop statement because it has been declared
inside the inner for -loop statement and its scope is local to that inner for -loop statement. Listing 5-1 contains the
complete code for the discussion in this section. The program makes sure not to print extra tabs and new line characters.
Listing 5-1. Using a for Loop to Print a 3x3 Matrix
// PrintMatrix.java
package com.jdojo.statement;
public class PrintMatrix {
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print(i + "" + j);
// Print a tab, except for the last number in a row
if (j < 3) {
System.out.print("\t");
}
}
// Print a new line, except after the last line
if (i < 3) {
System.out.println();
}
}
}
}
11 12 13
21 22 23
31 32 33
Search WWH ::




Custom Search