Find Second Largest Element in an Array in C
Write a C program to find second largest element in an array.
- Takes input for an array and ensures it has at least two elements.
- Initializes the first and largest elements using the first two array values.
- Traverses the array to update first and second based on comparisons.
- Prints the second largest element, or a message if it doesn't exist.
Example : pgm.c
#include <stdio.h> int main() { int n, arr[100], first, second; printf("Enter number of elements: "); scanf("%d", &n); if (n < 2) { printf("At least two elements are required.\n"); return 1; } printf("Enter %d elements:\n", n); for(int i = 0; i < n; i++) { scanf("%d", &arr[i]); } // Initialize first and second if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } for(int 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]; } } if (first == second) { printf("No second largest element found.\n"); } else { printf("Second largest element: %d\n", second); } return 0; }
Output:
Enter number of elements: 4
Enter 4 elements:
15
66
77
99
Second largest element: 77
Enter 4 elements:
15
66
77
99
Second largest element: 77