Java Reference
In-Depth Information
50 degrees
Fahrenheit. But a much more daunting problem is the wide range of values; it ranges
from a minimum of
that the average daily surface temperature on the Moon is a chilly
240 degrees to a maximum of 250 degrees.
To compute the maximum of a sequence of values, you can keep track of the
largest value you've seen so far and use an if statement to update the maximum if
you come across a new value that is larger than the current maximum. This approach
can be described in pseudocode as follows:
initialize max.
for (all numbers to examine) {
obtain "next".
if (next > max) {
max = next.
}
}
Initializing the maximum isn't quite as simple as it sounds. For example, novices
often initialize max to 0 . But what if the sequence of numbers you are examining is
composed entirely of negative numbers? For example, you might be asked to find the
maximum of this sequence:
84,
7,
14,
39,
410,
17,
41,
9
The maximum value in this sequence is -7, but if you've initialized max to 0 , the
program will incorrectly report 0 as the maximum.
There are two classic solutions to this problem. First, if you know the range of the
numbers you are examining, you can make an appropriate choice for max . In that
case, you can set max to the lowest value in the range. That seems counterintuitive
because normally we think of the maximum as being large, but the idea is to set max
to the smallest possible value it could ever be so that anything larger will cause max
to be reset to that value. For example, if you knew that the preceding sequence of
numbers were temperatures in degrees Fahrenheit, you would know that they could
never be smaller than absolute zero (around
460 degrees Fahrenheit), so you could
initialize max to that value.
The second possibility is to initialize max to the first value in the sequence. That won't
always be convenient because it means obtaining one of the numbers outside the loop.
When you combine these two possibilities, the pseudocode becomes:
initialize max either to lowest possible value or to first value.
for (all numbers to examine) {
obtain "next".
if (next > max) {
max = next;
}
}
Search WWH ::




Custom Search