Common Array Algorithms

This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.

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