Java Reference
In-Depth Information
Continued from previous page
for (int i = 1; i <= 20; i++) {
System.out.println("Hi!");
}
System.out.println("Ho!");
Only the first println is considered to be in the body of the for loop. The
second println is considered to be outside the loop. So, this code would produce
20 lines of output that all say “Hi!” followed by one line of output that says “Ho!”
To include both println s in the body, you need curly braces around them:
for (int i = 1; i <= 20; i++) {
System.out.println("Hi!");
System.out.println("Ho!");
}
for Loop Patterns
In general, if you want a loop to iterate exactly n times, you will use one of two stan-
dard loops. The first standard form looks like the ones you have already seen:
for (int <variable> = 1; <variable> <= n; i++) {
<statement>;
<statement>;
...
<statement>;
}
It's pretty clear that this loop executes n times, because it starts at 1 and continues
as long as it is less than or equal to n. For example, this loop prints the numbers
1 through 10:
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
Because it uses a print instead of a println statement, it produces a single line
of output:
1 2 3 4 5 6 7 8 9 10
Often, however, it is more convenient to start our counting at 0 instead of 1 . That
requires a change in the loop test to allow you to stop when n is one less:
 
Search WWH ::




Custom Search