C Program to Find Second Largest Number in an Array

The following C program finds the second largest element present in an array. The program iterates through an array and compares each element in an array.

For example:

Input: arr[] = {5, 85, 19, 6, 99, 45}
Output: The second largest element is 85.


C Program to Find Second Largest Number in an Array

//C Program to find Second largest Number in an Array

#include <stdio.h>
#include <limits.h>

int main()
{
   int arr[30], i, size, largest, second;

   printf("Enter the size of an array: \n");
   scanf("%d", &size);

   printf("Enter %d elements of an Array:\n", size);

   for (i = 0; i < size; i++)
   {
      scanf("%d", &arr[i]);
   }

   // largest and second largest initialized with minimum possible value
   largest = second = INT_MIN;

   //iterate through the array
   for (i = 0; i < size; i++)
   {
      //if arr element is greater than largest then
      //swap the value with largest and second largest with second.
      if (arr[i] > largest)
      {
         second = largest;
         largest = arr[i];
      }
      else if (arr[i] > second && arr[i] < largest)
      {
         second = arr[i];
      }
   }

   printf("Largest element: %d", largest);
   printf("\nSecond Largest element: %d", second);

   return 0;
}

Output:

Enter the size of an array:
5
Enter 5 elements of an Array:
12
56
8
19
88
Largest element: 88
Second Largest element: 56

Go through more C programming with various topics: