Common Array Algorithms

This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.

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 doubles, 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:

The program could be written with an enhanced for loop. Replace the for loop in the above program:

for (  val :  )

Now replace the loop body:

 +=  ;