Common Array Algorithms

10. Complete Max Program


Answer:

The complete program is given below.

Complete Max Program

Here is the program. Examine how the if statement changes max.

class MaxAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if ( array[ index ] > max )    // examine the current element
        max = array[ index ];        // if it is the largest so far, change max

    }
      
    System.out.println("The maximum of this array is: " + max );
  }
}      

Question 10:

What is the maximum of this list of integers:

-45,  -23,  -87,  -56,  -92,  -12,  -36