Java Reference
In-Depth Information
The second control element in a for loop is a logical expression which is checked at the beginning of
each iteration through the loop. If the expression is true , the loop continues, and as soon as it is
false the loop is finished. In our program the loop ends when i is greater than the value of limit .
The third control element in a for loop typically increments the loop variable, as we have in our
example. You can also put multiple expressions here too, so we could rewrite the above code fragment,
which added j to the loop, as:
for (int i = 1, int j = 0; i <= limit; i++, j++) {
sum+=i*j; // Add the current value of i*j to sum
}
Again, there can be several expressions here, and they do not need to relate directly to the control of
the loop. We could even rewrite the original loop for summing integers so that the summation occurs in
the loop control element:
for (int i = 1; i <= limit; sum += i, i++) {
;
}
Now the loop statement is empty - you still need the semi-colon to terminate it though. It doesn't really
improve things though and there are hazards in writing the loop this way. If you forget the semi-colon
the next statement will be used as the loop statement, which is likely to cause chaos. Another potential
problem arises if you happen to reverse the sequence of adding to sum and incrementing i , as follows:
for (int i = 1; i <= limit; i++, sum += i) { // Wrong!!!
;
}
Now you will generate the wrong answer. This is because the expression i++ will be executed before
sum += i , so the wrong value of i is used.
You can omit any or all of the elements that control the for loop, but you must include the semi-
colons. It is up to you to make sure that the loop does what you want. We could write the loop in our
program as:
for(int i = 1; i <= limit; ) {
sum += i++; // Add the current value of i to sum
}
We have simply transferred the incrementing of i from the for loop control to the loop statement. The
for loop works just as before. However, this is not a good way to write the loop, as it makes it much
less obvious how the loop counter is incremented.
Counting Using Floating Point Values
You can use a floating point variable as the loop counter if you need to. This may be needed when you
are calculating the value of a function for a range of fractional values. Suppose you wanted to calculate
the area of a circle with values for the radius from 1 to 2 in steps of 0.2. You could write this as:
Search WWH ::




Custom Search