Answer DC21

#include <stdio.h>
#include <stdlib.h>

/* Puzzle 21 -- find the largest element in an integer array */

int findLargest( int size, int arr[] )
{
  int j;
  int max;
  
  max = arr[ 0 ];
  for ( j = 1; j < size; j++ )
  {
    if ( arr[ j ] > max ) max = arr[ j ];
  }
  
  return max;
}

/* Generate a random integer  min <= r <= max */
int randInt( int min, int max )
{
  return (rand()*(max-min+1))/(RAND_MAX+1) + min ;
}

void fillArrayRandom( int size, int arr[], int low, int high )
{
  int j;
  for ( j=0; j < size; j++ )
    arr[j] = randInt( low, high );
}

void printArray( int size, int arr[] )
{
  const int N = 10;
  int j;
  
  for ( j=0; j < size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

int main()
{
  const int SIZE = 60;
  int x[ SIZE ];
  int max;
  
  srand( time(NULL) );
  fillArrayRandom( SIZE, x, 0, 99 );
  printArray( x, SIZE );
  printf("\n");
  max = findLargest( SIZE, x );
  printf("Max = %d\n", max );
    
  printf("\n");
  system("pause");	
  return 0;
}

Comments: Initialize the maximum element by max = arr[ 0 ] . Don't initialize it to zero (since the array might contain only negative elements, and its maximum would be less than zero.) Sometimes people initilize max to -9999, but this also is also unwise, since even that value might be greater than than the maximum element in the array.

But what if the array has no elements, so that size==0? Then the statement max = arr[ 0 ] would attempt to access an element that does not exist, and the program might crash or do something unexpected. Perhaps max should be initialized to INT_MIN, the value of the most negative integer. But now the function would report that an array of size zero has a maximum element.

Possibly the best thing to do is write the function as it is, but to be careful to call it only with arrays that have one or more elements.



Back to Puzzle Home