Java Reference
In-Depth Information
Nested for Loops
The for loop controls a statement, and the for loop is itself a statement, which
means that one for loop can control another for loop. For example, you can write
code like the following:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; j++) {
System.out.println("Hi there.");
}
}
This code is probably easier to read from the inside out. The println statement
produces a single line of output. The inner j loop executes this statement five times,
producing five lines of output. The outer i loop executes the inner loop 10 times,
which produces 10 sets of 5 lines, or 50 lines of output. The preceding code, then, is
equivalent to
for (int i = 1; i <= 50; i++) {
System.out.println("Hi there.");
}
This example shows that a for loop can be controlled by another for loop. Such a
loop is called a nested loop. This example wasn't very interesting, though, because
the nested loop can be eliminated.
Now that you know how to write for loops, you will want to be able to produce
complex lines of output piece by piece using the print command. Recall from
Chapter 1 that the print command prints on the current line of output without going
to a new line of output. For example, if you want to produce a line of output that has
80 stars on it, you can use a print command to print one star at a time and have it
execute 80 times rather than using a single println.
Let's look at a more interesting nested loop that uses a print command:
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(j + " ");
}
}
We can once again read this from the inside out. The inner loop prints the value of
its control variable j as it varies from 1 to 3 . The outer loop executes this six different
times. As a result, we get six occurrences of the sequence 1 2 3 as output:
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
 
Search WWH ::




Custom Search