Java Reference
In-Depth Information
PROGRAMMING EXAMPLE:
Largest Number
In this programming example, the method
larger
is used to determine the
largest number from a set of numbers, in this case, the largest number from a set of
10 numbers. You can easily modify this program to accommodate any set of numbers.
Input:
A set of 10 numbers
Output:
The largest of 10 numbers
Suppose that the input data is:
PROBLEM
ANALYSIS
AND
ALGORITHM
DESIGN
15 20 7 8 28 21 43 12 35 3
Read the first number of the data set. Because this is the only number read to this
point, you can assume that it is the largest number and call it
max
. Next, read the
second number and call it
num
. Now compare
max
and
num
, and store the larger
number into
max
. Now
max
contains the larger of the first two numbers. Next, read
the third number. Compare it with
max
and store the larger number into
max
. At this
point,
max
contains the largest of the first three numbers. Read the next number,
compare it with
max
, and store the larger into
max
. Repeat this process for each
remaining number in the data set. Eventually,
max
will contain the largest number in
the data set. This discussion translates into the following algorithm:
1. Get the first number. Because this is the only number that you have
read so far, it is the largest number so far. Save it in a variable called
max
.
2. For each remaining number in the list:
a. Get the next number. Store it in a variable called
num
.
b. Compare
num
and
max
.If
max < num
, then
num
is the new
largest number; update the value of
max
by copying
num
into
max
.If
max >= num
, discard
num
; that is, do nothing.
3. Because
max
now contains the largest number, print it.
To find the larger of two numbers, the program uses the method
larger
.
7
COMPLETE PROGRAM LISTING
//********************************************************
// Author D.S. Malik
//
// Program: Largest number
// This program determines the largest number of a set of
// 10 numbers.
//********************************************************
Search WWH ::
Custom Search