0
0
CProgramBeginner · 2 min read

C Program to Find Second Largest Element in Array

To find the second largest element in an array in C, initialize two variables for largest and second largest, then iterate through the array updating them using if conditions; for example: if(arr[i] > largest) { second = largest; largest = arr[i]; } else if(arr[i] > second && arr[i] != largest) { second = arr[i]; }.
📋

Examples

Inputarr = {5, 3, 9, 1, 6}
OutputSecond largest element is 6
Inputarr = {10, 10, 10}
OutputSecond largest element does not exist
Inputarr = {1, 2}
OutputSecond largest element is 1
🧠

How to Think About It

To find the second largest number, first find the largest number by comparing each element. Then keep track of the next biggest number that is less than the largest. This way, after checking all elements, you have the largest and second largest values.
📐

Algorithm

1
Initialize two variables: largest and second largest with minimum possible values.
2
Traverse each element of the array.
3
If current element is greater than largest, update second largest to largest and largest to current element.
4
Else if current element is greater than second largest and not equal to largest, update second largest.
5
After traversal, check if second largest was updated; if yes, return it, else indicate it does not exist.
💻

Code

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

int main() {
    int arr[] = {5, 3, 9, 1, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    int largest = INT_MIN, second = INT_MIN;

    for(int i = 0; i < n; i++) {
        if(arr[i] > largest) {
            second = largest;
            largest = arr[i];
        } else if(arr[i] > second && arr[i] != largest) {
            second = arr[i];
        }
    }

    if(second == INT_MIN) {
        printf("Second largest element does not exist\n");
    } else {
        printf("Second largest element is %d\n", second);
    }
    return 0;
}
🔍

Dry Run

Let's trace the array {5, 3, 9, 1, 6} through the code to find the second largest element.

1

Initialize variables

largest = INT_MIN, second = INT_MIN

2

Check element 5

5 > largest(INT_MIN), so second = INT_MIN, largest = 5

3

Check element 3

3 > second(INT_MIN) and 3 != largest(5), so second = 3

4

Check element 9

9 > largest(5), so second = largest(5), largest = 9

5

Check element 1

1 > second(5)? No, no change

6

Check element 6

6 > second(5) and 6 != largest(9), so second = 6

7

End of array

largest = 9, second = 6

IterationElementLargestSecond Largest
155INT_MIN
2353
3995
4195
5696
💡

Why This Works

Step 1: Initialize largest and second largest

Start with smallest possible values so any array element will be larger and update these variables.

Step 2: Update largest and second largest

When a bigger element than largest is found, shift largest to second largest and update largest.

Step 3: Handle duplicates and smaller elements

Only update second largest if element is less than largest but greater than current second largest.

🔄

Alternative Approaches

Sort the array and pick second last element
c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int arr[] = {5, 3, 9, 1, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    qsort(arr, n, sizeof(int), compare);
    int largest = arr[n-1];
    int second = INT_MIN;
    for(int i = n-2; i >= 0; i--) {
        if(arr[i] != largest) {
            second = arr[i];
            break;
        }
    }
    if(second == INT_MIN) {
        printf("Second largest element does not exist\n");
    } else {
        printf("Second largest element is %d\n", second);
    }
    return 0;
}
This method is simpler but slower due to sorting (O(n log n)) compared to single pass.
Use two passes: first find largest, then find max less than largest
c
#include <stdio.h>
#include <limits.h>

int main() {
    int arr[] = {5, 3, 9, 1, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    int largest = INT_MIN, second = INT_MIN;
    for(int i = 0; i < n; i++) {
        if(arr[i] > largest) largest = arr[i];
    }
    for(int i = 0; i < n; i++) {
        if(arr[i] > second && arr[i] < largest) second = arr[i];
    }
    if(second == INT_MIN) {
        printf("Second largest element does not exist\n");
    } else {
        printf("Second largest element is %d\n", second);
    }
    return 0;
}
Two passes make logic clear but less efficient than single pass.

Complexity: O(n) time, O(1) space

Time Complexity

The program scans the array once, so time complexity is O(n), where n is the number of elements.

Space Complexity

Only a few variables are used, so space complexity is O(1), constant extra space.

Which Approach is Fastest?

The single pass method is fastest and most efficient compared to sorting or two-pass methods.

ApproachTimeSpaceBest For
Single pass scanO(n)O(1)Fastest, minimal memory
Sorting then pickO(n log n)O(1)Simple code, slower for large arrays
Two passesO(n)O(1)Clear logic, slightly less efficient
💡
Initialize largest and second largest to very small values before scanning the array.
⚠️
Not handling the case when all elements are equal, causing incorrect second largest results.