Introduction to 1-Dimensional Array
We can represent a collection of data items using an array. Java arrays have the following characteristics:
- Once created, the size of an array is fixed. We can access the size of the array using the array’s
length
attribute. - The data items represented by the array are indexed consecutively from
0
tolength-1
. - We can access each data item or more frequently array element using its index.
- The time to access each data item is always equal or almost equal.
Exercise 1. Analyzing a Collection of Numbers
Given a list of numbers, e.g., 100 numbers, find out how many numbers are above the average. Assuming the numbers can be floating point values, the program should display the average and the counting results. Before we take a look at the testing results below that also exhibits the format of the output, let’s discuss about the design of the program:
- We expect that the first user input should be an integer that indicates the number of floating point values that follows, which tells us the size of the array we should initialize.
- We read the floating values to an array.
- We compute the avearge of the values in the array.
- We count the number of values that is above the average.
For convenience, we don’t wish to enter a large number of floating values repeatedly, for this, we create a file that consists of all user inputs and leverage the I/O redirection functionalility provided an operating system to feed the program with the inputs from the file.
$ java AnalyzeNumbers < numbers1.txt
4 values are above the average of 6.750000