Find two largest elements in an array
C program to find two largest elements in a one dimensional array.
Program
#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define MAX 50
void main()
{
int arr[MAX];
int i, n, max, second, flag;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&arr[i]);
}
max = arr[0];
second = INT_MIN;
flag = 0;
for(i=0;i<n;i++)
{
if(arr[i] > max)
{
second = max;
max = arr[i];
flag = 1;
}
else if(arr[i] > second && arr[i] != max)
{
second = arr[i];
flag = 1;
}
}
if(flag == 0)
{
printf("\nLargest element of the array is\t:%d",max);
printf("\nSecond Largest element does not exist");
}
else
{
printf("\nLargest element of the array is\t:%d",max);
printf("\nSecond Largest element of the array is\t:%d",second);
}
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :8
Enter the elements
Element 1 :12
Element 2 :45
Element 3 :41
Element 4 :23
Element 5 :56
Element 6 :47
Element 7 :89
Element 8 :85
Largest element of the array is :89
Second Largest element of the array is :85
********** Run2 **********
Enter the number of elements in the array :4
Enter the elements
Element 1 :5
Element 2 :5
Element 3 :5
Element 4 :5
Largest element of the array is :5
Second Largest element does not exist