Complete Summing Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The complete program is given below.

Complete Summing Program

The variable total is declared to be of double type, since the sum of the doubles in the array will be a double. It is initialized to zero. Sums should be initialized to zero as a matter of course. (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.)
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 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:

 +=  ;