Java Reference
In-Depth Information
24
for
(
int
i = 0; i < temps.length; i++) {
25
if
(temps[i] > average) {
26 above++;
27 }
28 }
29
30 // report results
31 System.out.println();
32 System.out.println("Average = " + average);
33 System.out.println(above + " days above average");
34 }
35 }
Here is a sample execution of the program:
How many days' temperatures?
9
Day 1's high temp:
75
Day 2's high temp:
78
Day 3's high temp:
85
Day 4's high temp:
71
Day 5's high temp:
69
Day 6's high temp:
82
Day 7's high temp:
74
Day 8's high temp:
80
Day 9's high temp:
87
Average = 77.88888888888889
5 days above average
Most of the algorithms we have seen so far have involved
sequential access.
Sequential Access
Manipulating values in a sequential manner from first to last.
A
Scanner
object is often all you need for a sequential algorithm, because it
allows you to access data by moving forward from the first element to the last. But as
we have seen, there is no way to reset a
Scanner
back to the beginning. The sample
program we just studied uses an array to allow a second pass through the data, but
even this is fundamentally a sequential approach because it involves two forward
passes through the data.
An array is a powerful data structure that allows a more sophisticated kind of
access known as
random access:
Search WWH ::
Custom Search