Java Reference
In-Depth Information
7.4.4 Summing the Elements of an Array
Often, the elements of an array represent a series of values to be used in a calculation. If,
for example, they represent exam grades, a professor may wish to total the elements of the
array and use that sum to calculate the class average for the exam. The GradeBook examples
in Figs. 7.14 and 7.18 use this technique.
Figure 7.5 sums the values contained in a 10-element integer array. The program
declares, creates and initializes the array at line 8. The for statement performs the calcu-
lations. [ Note: The values supplied as array initializers are often read into a program rather
than specified in an initializer list. For example, an application could input the values from
a user or from a file on disk (as discussed in Chapter 15, Files, Streams and Object Serial-
ization). Reading the data into a program (rather than “hand coding” it into the program)
makes the program more reusable, because it can be used with different sets of data.]
1
// Fig. 7.5: SumArray.java
2
// Computing the sum of the elements of an array.
3
4
public class SumArray
5
{
6
public static void main(String[] args)
7
{
8
int [] array = { 87 , 68 , 94 , 100 , 83 , 78 , 85 , 91 , 76 , 87 };
9
int total = 0 ;
10
11
// add each element's value to total
for ( int counter = 0 ; counter < array.length; counter++)
total += array[counter];
12
13
14
15
System.out.printf( "Total of array elements: %d%n" , total);
16
}
17
} // end class SumArray
Total of array elements: 849
Fig. 7.5 | Computing the sum of the elements of an array.
7.4.5 Using Bar Charts to Display Array Data Graphically
Many programs present data to users in a graphical manner. For example, numeric values
are often displayed as bars in a bar chart. In such a chart, longer bars represent proportion-
ally larger numeric values. One simple way to display numeric data graphically is with a
bar chart that shows each numeric value as a bar of asterisks ( * ).
Professors often like to examine the distribution of grades on an exam. A professor
might graph the number of grades in each of several categories to visualize the grade dis-
tribution. Suppose the grades on an exam were 87, 68, 94, 100, 83, 78, 85, 91, 76 and 87.
They include one grade of 100, two grades in the 90s, four grades in the 80s, two grades
in the 70s, one grade in the 60s and no grades below 60. Our next application (Fig. 7.6)
stores this grade distribution data in an array of 11 elements, each corresponding to a cat-
egory of grades. For example, array[0] indicates the number of grades in the range 0-9,
array[7] the number of grades in the range 70-79 and array[10] the number of 100
 
 
 
Search WWH ::




Custom Search