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.

18. Summing the numbers in an Array


Answer:

class MinAlgorithm
{
  public static void main ( String[] args ) 
  {
    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
    min = array[0]; 

    // scan the array
    for ( int val : array )
    { 
       if (   val < min ) 
         min = val ; 
    }
      
    System.out.println("The minimum of this array is: " + min );
  }
}         

Summing the numbers in an Array

Say that you want to compute the sum of a list of numbers. This algorithm sounds much like those of the previous two programs.

The sum is initialized to zero. Then the loop adds each element of the array to the sum.

You could initialize the sum to the first number and then have the loop add the remaining numbers. But there is no advantage in doing this.

Here is the program. The array contains values of type double. Assume that the array contains at least one element.


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
        total =       ;

    // add each element of the array to the total
    for ( int index=0; index < array.length; index++ )
    { 

      total =     ;

    }
      
    System.out.println("The total is: " + total );
  }
}


Question 18:

Complete the program by filling in the blanks.