Find out second largest element in array C program

Find second largest element in given array. For example if arr is {2,6,3,12,7,9,4} then second largest element is 9. Our task is find out this element.

First we will declare two variable max and second_max and initialize max and second_max to INT_MIN. Now compare max and second_max with array elements. If array element is greater than max then update second_max to max and max to arr element. See below the explanation.

max=INT_MIN and second_max=INT_MIN;
now arr[0]=2 and arr[0] > max;
max=arr[0], second_max=max;

arr[1]=6 > max;
second_max=max => second_max=2;
 max=6;

arr[2]=3<max but arr[2]>second_max and arr[2]!=max;
so second_max=3;

arr[3]=12 > max ;
now second_max=max;
max = 12;

arr[4]=7 <max but arr[4] = 7 > second_max and arr[4]!=max;
so second_max= 7;

/* C Program to find second max element in array */
#include<stdio.h> 
#include<limits.h>  
int FindSecondMax(int arr[],int size)
{
 int i,max=INT_MIN,second_max=INT_MIN;
 
 for(i=0;i<size;i++)
 {
  if(arr[i]>max)
  {
   second_max=max;
   max=arr[i];
  }
  else
  if(arr[i]>second_max&&arr[i]!=max)
  {
   second_max=arr[i];
  }
 }
 
 return second_max;
}
 
int main()
{
 int arr[100];
 int i,n,max,second_max;
 /*number of elements in array */
 printf("Enter number for elements: ");
 scanf("%d",&n);
 
 printf("Enter %d elements: ",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 
 second_max=FindSecondMax(arr,n);
 
 printf("Second max = %d",second_max);
 return 0;
}

Popular posts from this blog