A good answer might be:

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 );
  }
}      

It is well worth your time to "copy-paste-and-run" this program. Once you have it running see if you can "break" it by initializing the array to different values:

  • Put the largest element at the beginning.
  • Put the largest element at the end.
  • Put in more than one copy of the largest element.
  • Put in an extremely large element.
  • Make all elements the same.
  • Make all elements negative.
  • Make all elements zero.
Sometimes a program will work for the data a programmer was thinking about when the program was written, but not for the actual data the program will be used with.

Here is a classic bug for this type of program:

Change the test part of the loop to index < array.length-1
The program is now suffering from the notorious "off-by-one" error---the most common bug in programming.

QUESTION 10:

  1. Will the program (with the 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?

Click Here after you have answered the question