Answer:

The complete program is given below.

Complete Max Program

Here is the program. Carefully examine how the if statement is used to change 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 );
  }
}      

Try to run this program. Once you have it running see if you can "break" it by initializing the array to different values:

Is the correct maximum found in each case? Sometimes a program works for the data a programmer was thinking about when the program was written, but not for all the kinds of data the program is used with.

QUESTION 10:

Here is a classic bug for this type of program: change the test part of the for to

index < array.length-1
  1. Will the program (with this classic bug) find the correct maximum of the data that is given in the initializer list?
  2. When will the program not work correctly?
  3. Is it obvious that there is a bug?