Divide the sum by the number of elements.
Of course, this is assuming that there are more than zero elements. Dividing by zero causes a run-time error. Here is the program with some additional statements for computing the average of the elements:
class SumArray { public static void main ( String[] args ) { double[] array = { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ; // declare and initialize the total double total = 0.0 ; // add each element of the array to the total for ( int index=0; index < array.length; index++ ) { total = total + array[ index ] ; } if ( array.length _______ 0 ) { System.out.println("The total is: " + total ); System.out.println("The average is: " + total / _______ ); } else System.out.println("The array contains no elements." ); } }
It might look a little strange to test if array
contains any elements,
since it is obvious that it does.
However, in a more realistic program the array will come from some
external source, and sometimes the array will have length zero.