The beginning (index 0) element in an array will never be larger than the maximum element in that array. (It might be the maximum element of the array; but this is fine.)
max = array[0];
This way of initializing max
assumes that there is at least one
element in the array.
If there is not, the java system will detect that the index "0" is
out of bounds and throw an exception.
Here is the program so far.
It has initialized max
to
the first element in the array.
The for
loop is set up to look at every
element in the array, starting with the beginning element,
to see if that element "beats" the current maximum.
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 ( ____________________ ) // 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 would be OK (and maybe preferable) to initialize index
at 1.
But the program as written works fine (as soon as you fill in the blank.)