Thursday, June 9, 2011

Write a program to find the max and second max


This is little tricky, but not difficult. easiest way to do this is to sort the array and then find the answer. But that not expected out of you.

The algorithm here is take thefirst element as the max and second max. Then loop through all elements

  1. If the number is larger than max then make it max, and make old max to second max.
  2. Else if it is more than second max then make it the second max.
  3. In all other cases drop that number
Here goes the code for your reference.

/*
** Write a program for finding the max and second max 
** of an array of given size */

#define SIZE 10

int main(void)
{
    int array[SIZE] = {10, 5, 16, 2, 1, 2, 3, 18, 21, 4};
    int i, max, sec_max;

    max  = sec_max = array[0];

    for(i=0; i< SIZE; i++)
    {
        if(array[i] > max) {
            sec_max = max;
            max = array[i];
        }
        else if(array[i] > sec_max)
            sec_max = array[i];
    }

    printf("max =  %d, sec max = %d", max, sec_max);
}

No comments:

Post a Comment