Answer:

  1. Will the program (with the classic bug) find the correct maximum of the data that is given in the initializer list?
    • Yes—for this particular set of data, the program will compute the correct maximum.
  2. When will the program not work correctly?
    • When the maximum element of the array is in the very last cell (and only occurs once in the array.)
  3. Is is obvious that there is a bug?
    • No—for most data the program works OK. If it were tested just a few times, it might pass every test.

Finding the Minimum in an Array

With a ten-element initializer list, the buggy program will fail about one time in ten (assuming random lists of data). It might not even be clear when it did fail, because the answer it computes is close to the maximum. With a ten thousand element array, the program will fail about one time in ten thousand! Off-by-one errors can be very subtle.

Here is a program that finds the minimum of an array. It is similar to the maximum-finding program:

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

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if  ;

         ;

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

QUESTION 11:

Fill in the blanks. Select from the following phrases.

array[8]
array[0]
array[ index ]
> min
< min
min =
index++

(Hint: only some of the phrases are used.)