Problem: Write a C program to find and print the second largest element of an array.

Example:

Input:   1 2 2 6 8 9
Output:  8

Input:   15 5 8 30 89
Output:  30

To solve the problem, we will find the largest element in the array (i.e. max).

We will compare each element of the array with the max and whenever we encounter a number greater than max, we update the max variable with the new maximum value but store the old maximum value in another variable secondmax.

By doing so, at the end of the array traversal, the secondmax variable will hold the second-largest value of the array.

#include<stdio.h>
#include<limits.h>
 
int main()
{
  int n, array[20];
 
  printf("Enter the size: ");
  scanf("%d",&n);
 
  printf("Enter the elements: ");
  for(int i=0; i<n; i++){
    scanf("%d",&array[i]);
  }
    
  //initialize max and second max with the minimum possible value
  int max = INT_MIN;
  int secondmax = INT_MIN;
    
  //Iterate through array elements
  for(int i=0; i<n; i++){
    /*
      *If element is greater than max then
      *update max with new value and secondmax with old
    */
    if(array[i]>max){
      secondmax = max;
      max = array[i];
    }
    
    /*
      *Otherwise if element is less than max but
      *greater than secondmax, then only update secondmax
    */
    else if(array[i]<max && array[i]>secondmax){
      secondmax = array[i];
    }
  }
 
  printf("Second largest element is %d",secondmax);
 
  return 0;
}

Output:

Enter the size: 5
Enter the elements: 1 4 6 8 7
Second largest element is 7


Explanation:

While looping through the array, we are comparing each array element with the largest number (i.e. max).

If the element is greater than max then max value become second largest (i.e. secondmax).

If the array element is less than max but greater than secondmax then that particular element is the second largest element.

In this tutorial, we learned to find the second largest element of the array in the Cprogramming language.

Leave a Reply