Java Reference
In-Depth Information
On the first execution of the
for
loop, we read in a value of
3.2
from the user and
add this value to
sum
:
sum 3.2
next 3.2
The second time through the loop, we read in a value of
4.7
and add this to the
value of
sum
:
sum 7.9
next 4.7
Notice that the
sum
now includes both of the numbers entered by the user, because
we have added the new value,
4.7
, to the old value,
3.2
. The third time through the
loop, we add in the value
5.1
:
sum 13.0
next 5.1
Notice that the variable
sum
now contains the sum of the first three numbers
(
3.2 + 4.7 + 5.1
). Now we read in
9.0
and add it to the sum:
sum 22.0
next 9.0
Then we add in the fifth value,
2.4
:
sum 24.4
next 2.4
Finally, we add in the sixth value,
3.1
:
sum 27.5
next 3.1
We then exit the
for
loop and print the value of
sum
.
There is an interesting scope issue in this particular program. Notice that the variable
sum
is declared outside the loop, while the variable
next
is declared inside the loop. We
have no choice but to declare
sum
outside the loop because it needs to be initialized and it
is used after the loop. But the variable
next
is used only inside the loop, so it can be
declared in that inner scope. It is best to declare variables in the innermost scope possible.
The cumulative sum algorithm and variations on it will be useful in many of the
programming tasks you solve. How would you do a cumulative product? Here is the
pseudocode:
product = 1.
for (all numbers to multiply) {
obtain "next".
product *= next.
}
Another common programming task is to keep track of the maximum and/or mini-
mum values in a sequence. For example, consider the task of deciding whether it will
be viable to build a living area on the Moon inhabited by humans. One obstacle is
Search WWH ::
Custom Search