Question: Write C code to find maximum and second maximum in an array

Solution: Naive approach.

On first look, this problem appears to be quite simple. Indeed, the solution is possible through a very simple approach: Find the largest of the set, eliminate it and again find the largest of the remainder of the elements.

#include

#define MAXELT 10001

void main()
{
int i=-1,n=0,largest,slargest;
char t[10];
void largest_and_second_largest(int[],int,int&,int&);
int list[MAXELT];

do { //read the list of numbers
if (i!=-1)
list[i++]=n;
else
i++;
printf("\nEnter the numbers ");
gets(t);
if (sscanf(t,"%d",&n)<1)
break;
} while (1);

largest_and_second_largest(list,i,largest,slargest);

printf("The largest of the list is %d and the second largest is %d.",largest,slargest);
}

//pre: there must be atleast two numbers in the list
void largest_and_second_largest(int list[],int n,int &largest,int &slargest)
{
int largeindex=0,i;
largest=list[0];
for (i=1;i if (list[i]>largest) {
largest=list[i];
largeindex=i; //to eliminate the largest later
}
//we have found the largest, stored in largest and its
//index stored in largeindex. Now find the second largest
//ignoring the largest.
if (largeindex==0)
slargest=list[1];
else
slargest=list[0];
for (i=0;i if (list[i]>slargest && i!=largeindex)
slargest=list[i];
//we have found the second largest
}