Common Array Algorithms
19. Complete Summing Program
Answer:
The complete program is given below.
Complete Summing Program
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 ] ; } System.out.println("The total is: " + total ); } } |
The variable total
is declared to be of type double
because the elements in the array are double
s, as is their sum. total
is initialized to zero. Sums should always be initialized to zero.
(You could, perhaps, initialize total
to the first element of the array, and then use the loop to add in the remaining elements. But this is much less clear than the expected way of doing things and is an open invitation to bugs.)
The program visits each element of the array, in order, adding each to the total. When the loop exits, total
will be correct. The statement
total = total + array[ index ] ;
would not usually be used. It is more common to use the +=
operator:
total += array[ index ] ;
Question 19: