C program to find second largest number in an array

Write a C program to find the largest and second largest element in an array. How to find second largest element of an array in C programming language. Algorithm to find second largest element of an array.

Second largest in an array.


Required knowledge

Basic C programming, Array

Algorithm to find second largest element

The basic logic behind this problem can be divided in three steps:
  1. First assume that max1 and max2 are the first element of array (where max1 represents first maximum and max2 represents second maximum element) and after that run a loop from second element till N (where N is the size of the array).
  2. If the current element of array is greater than max1 then copy the value of max1 to max2 as a new maximum has been found. Also copy the value of current array element to max1.
  3. Else if the current array element is greater than max2 but is less than max1 then also copy the value of current array element to max2.

Algorithm to find second largest element in an array
%%Input : arr {Array in which largest is to be found}
          N {Size of the array}
Begin:
    max1arr[0];
    max2arr[0];
    For i ← 1 to N do
        If (arr[i] > max1) then
            max2max1;
            max1arr[i];
        End if
        Else if (arr[i] > max2) then
            max2arr[i];
        End if
    End for
End


Program

/**
 * C program to find second largest number in an array
 */

#include <stdio.h>
#include <limits.h> //For INT_MIN

#define MAX_SIZE 1000

int main()
{
    int arr[MAX_SIZE], N, i;
    int max1, max2;

    /*
     * Reads size and elements in the array
     */
    printf("Enter size of the array (1-1000): ");
    scanf("%d", &N);
    printf("Enter elements in the array: ");
    for(i=0; i<N; i++)
    {
        scanf("%d", &arr[i]);
    }

    max1 = max2 = INT_MIN;

    /*
     * Checks for first largest and second largest till N
     */
    for(i=0; i<N; i++)
    {
        if(arr[i] > max1)
        {
            /*
             * If current element of the array is first largest
             * then make current max as second max
             * and then max as current array element
             */
            max2 = max1;
            max1 = arr[i];
        }
        else if(arr[i] > max2)
        {
            /*
             * If current array element is less than first largest
             * but is greater than second largest then make it
             * second largest
             */
            max2 = arr[i];
        }
    }

    printf("First largest = %d\n", max1);
    printf("Second largest = %d", max2);

    return 0;
}


Output
Enter size of the array (1-1000): 10
Enter elements in the array: -7 2 3 8 6 6 75 38 3 2
First largest = 75
Second largest = 38

Happy coding ;)


You may also like

Labels: , , ,