Java Reference
In-Depth Information
for (int <variable> = 0; <variable> < n; i++) {
<statement>;
<statement>;
...
<statement>;
}
Notice that in this form when you initialize the variable to
0
, you test whether it is
strictly less than
n.
Either form will execute exactly
n
times, although there are some
situations where the zero-based loop works better. For example, this loop executes
10 times just like the previous loop:
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
Because it starts at
0
instead of starting at
1
, it produces a different sequence of 10
values:
0 1 2 3 4 5 6 7 8 9
Most often you will use the loop that starts at
0
or
1
to perform some operation a
fixed number of times. But there is a slight variation that is also sometimes useful.
Instead of running the loop in a forwards direction, we can run it backwards. Instead
of starting at
1
and executing until you reach
n
, you instead start at
n
and keep exe-
cuting until you reach
1
. You can accomplish this by using a decrement rather than an
increment, so we sometimes refer to this as a decrementing loop.
Here is the general form of a decrementing loop:
for (int <variable> = n; <variable> >= 1; <variable>--) {
<statement>;
<statement>;
...
<statement>;
}
For example, here is a decrementing loop that executes 10 times:
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
Because it runs backwards, it prints the values in reverse order:
10 9 8 7 6 5 4 3 2 1
Search WWH ::
Custom Search