Java Reference
In-Depth Information
}
In this fragment, I initialize an additional variable j , and, to make the loop vaguely sensible, I have mod-
ified the value to add the sum to i*j++ , which is the equivalent of i*(i-1) in this case. Note that j is
incremented after the product i*j has been calculated. You could declare other variables here, but note
that it would not make sense to declare sum at this point. If you can't figure out why, delete or comment
out the original declaration of sum in the example and put it in the for loop instead to see what happens.
The program won't compile — right? After the loop ends, the variable sum no longer exists, so you can't
reference it. This is because all variables that you declare within the loop control expressions are logic-
ally within the block that is the body of the loop; they cease to exist after the end of the block.
The second control element in a for loop is a logical expression that is checked at the beginning of each
iteration through the loop. If the expression is true , the loop continues, the loop body executes, 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 you have seen in the
example. You can put multiple expressions here, too, so you could rewrite the previous code fragment
that added j to the loop as:
for (int i = 1, 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. You 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 just have the semicolon to terminate it. The semicolon is op-
tional, but putting in shows that you meant the block to be empty. This version of the code doesn't really
improve things, though, as it's certainly not so easy to see what is happening and there are hazards in
writing the loop this way. If you were to reverse the sequence of adding to sum and incrementing i as
follows
for (int i = 1; i <= limit; ++i, sum += i) { // Wrong!!!
;
}
you would generate the wrong answer. This is because the expression ++i would 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 semicolons.
It is up to you to make sure that the loop does what you want. I could rewrite the loop in the program as:
for (int i = 1; i <= limit; ) {
sum += i++; // Add the current value of
i to sum
Search WWH ::




Custom Search