Java Reference
In-Depth Information
This loop executes a total of 201 times, producing the squares of all the integers
between -100 and +100 inclusive. The values used in the initialization and the test,
then, can be any integers. They can, in fact, be arbitrary integer expressions:
for (int i = (2 + 2); i <= (17 * 3); i++) {
System.out.println(i + " squared = " + (i * i));
}
This loop will generate the squares of all the integers between 4 and 51 inclusive.
The parentheses around the expressions are not necessary but improve readability.
Consider the following loop:
for (int i = 1; i <= 30; i++) {
System.out.println("+--------+");
}
This loop generates 30 lines of output, all exactly the same. It is slightly different
from the previous one because the statement controlled by the for loop makes no
reference to the control variable. Thus,
for (int i = -30; i <= -1; i++) {
System.out.println("+--------+");
}
generates exactly the same output. The behavior of such a loop is determined solely
by the number of iterations it performs. The number of iterations is given by
<ending value> - <starting value> + 1
It is much simpler to see that the first of these loops iterates 30 times, so it is better
to use that loop.
Now let's look at some borderline cases. Consider this loop:
for (int i = 1; i <= 1; i++) {
System.out.println("+--------+");
}
According to our rule it should iterate once, and it does. It initializes the variable i
to 1 and tests to see if this is less than or equal to 1 , which it is. So it executes the
println , increments i , and tests again. The second time it tests, it finds that i is no
longer less than or equal to 1 , so it stops executing. Now consider this loop:
for (int i = 1; i <= 0; i++) {
System.out.println("+--------+"); // never executes
}
 
Search WWH ::




Custom Search