C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Find second largest element

C Program: Find second largest element

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i;

    int first, second;

 

    // Input size of array

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Initialize first and second largest

    if (arr[0] > arr[1]) {

        first = arr[0];

        second = arr[1];

    } else {

        first = arr[1];

        second = arr[0];

    }

 

    // Find second largest

    for (i = 2; i < n; i++) {

        if (arr[i] > first) {

            second = first;

            first = arr[i];

        } else if (arr[i] > second && arr[i] != first) {

            second = arr[i];

        }

    }

 

    printf("\nThe second largest element is: %d\n", second);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 6
Enter 6 elements:
12 35 1 10 34 1

OUTPUT 2 :
The second largest element is: 34

Explanation

  1. The program first initializes the largest and second largest elements.
  2. It then iterates through the array:
    • If a number is greater than the current largest, update both first and second.
    • If it’s smaller than the largest but greater than second, update second.
  3. Finally, it prints the second largest number.