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.

20. Sum of No Elements


Answer:

for ( double val : array )
total += val ;

Sum of No Elements

Here is the revised program:

class SumArrayRevised
{

  public static void main ( String[] args ) 
  {
    double[] array =  {} ;

    // declare and initialize the total
    double total =    0.0 ;

    // add each element of the array to the total
    for ( double val : array )
      total += val ;
      
    System.out.println("The total is: " + total );
  }
} 

Question 20:

But the array has no elements!!   Will the program compile?   Will the program run?   What is the sum of an array with no elements?