Find Second largest element in the array

pull/824/head
Prashant Bhapkar 2022-08-29 20:39:31 +05:30
parent ff8d1c7441
commit 710d7bfbf6
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
//Second largest element in the array
#include<stdio.h>
#include<stdlib.h>
int second(int arr[],int size)
{
int max1=arr[0],max2;
for(int i=0;i<size;i++)
{
if(arr[i]>max1) //Find largest element in the array
{
max2=max1;
max1=arr[i];
}
else if (arr[i]>max2 && arr[i]<max1) // Find second largest element in the array
{
max2=arr[i];
}
}
printf("%d %d",max1,max2); // Print both first and second largest element in the array
}
int main()
{
int arr[]={2,5,1,12,18,88,23,45,4}; // Initialize array
int size=sizeof(arr)/sizeof(int); // Calculate array size
second(arr,size);
return 0;
}