Java Reference
In-Depth Information
Before the
for
loop begins,
maxIndex
is initialized to
0
and the
for
loop initializes
index
to
1
. In Table 9-1, we show the values of
maxIndex
,
index
, and certain array
elements during each iteration of the
for
loop:
TABLE 9-1
Values of
sales
Array Elements during
for
Loop Iterations
sales
[maxIndex]
sales
[index]
sales[maxIndex] <
sales[index]
index
maxIndex
1
0
12.50
8.35
12.50 < 8.35
is
false
12.50 < 19.60
is
true
;
maxIndex = 2
2
0
12.50
19.60
19.60 < 25.00
is
true
;
maxIndex = 3
3
2
19.60
25.00
4
3
25.00
14.00
25.00 < 14.00
is
false
25.00 < 39.43
is
true
;
maxIndex = 5
5
3
25.00
39.43
6
5
39.43
35.90
39.43 < 35.90
is
false
39.43 < 98.23
is
true
;
maxIndex = 7
7
5
39.43
98.23
8
7
98.23
66.65
98.23 < 66.65
is
false
9
7
98.23
35.64
98.23 < 35.64
is
false
After the
for
loop executes,
maxIndex = 7
, giving the index of the largest element in the
array
sales
. Thus,
largestSale = sales[maxIndex] = 98.23
.
In an array, if the largest element occurs more than once, then the previous
algorithm will find the index of the first occurrence of the largest element. The
algorithm to find the smallest element in an array is similar to the algorithm for
finding the largest element in an array. (See Programming Exercise 2 at the end of
this chapter.)
Now that we know how to declare and process arrays, let's rewrite the program that we
discussed in the beginning of this chapter. Recall that this program reads five numbers,
finds the sum, and prints the numbers in reverse order.
Search WWH ::
Custom Search