Java Reference
In-Depth Information
Note that when using pseudocode, we do not necessarily declare variables or worry
about the fine syntax details of Java. The only rule is that the pseudocode be precise
and clear enough for a good programmer to convert the pseudocode to syntactically
correct Java code.
As you will see, significant programs are written not as a single algorithm, but as a
set of interacting algorithms; however, each of these algorithms is normally designed in
pseudocode unless the algorithm is exceedingly simple.
EXAMPLE: Averaging a List of Scores
Display 3.8 shows a program that reads in a list of scores and computes their average.
It illustrates a number of techniques that are commonly used with loops.
The scores are all nonnegative. This allows the program to use a negative number as
an end marker. Note that the negative number is not one of the numbers being aver-
aged in. This sort of end marker is known as a sentinel value . A sentinel value need
not be a negative number, but it must be some value that cannot occur as a “real”
input value. For example, if the input list were a list of even integers, then you could
use an odd integer as a sentinel value.
To get the loop to end properly, we want the Boolean expression
sentinel
values
next >= 0
checked before adding in the number read. This way we avoid adding in the sentinel
value. So, we want the loop body to end with
next = keyboard.nextDouble( );
To make things work out, this in turn requires that we also place this line before the
loop. A loop often needs some preliminary statements to set things up before the loop
is executed.
Self-Test Exercises
22. What is the output produced by the following?
int n = 10;
while (n > 0)
{
System.out.println(n);
n = n - 3;
}
23. What output would be produced in Exercise 22 if the > sign were replaced with < ?
(continued)
Search WWH ::




Custom Search