#include <stdio.h>
#include <limits.h>
int findSecondLargest(int arr[], int n) {
if (n < 2) {
return -1; // Not enough elements
}
int first = INT_MIN, second = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] < first) {
second = arr[i];
}
}
return (second == INT_MIN) ? -1 : second; // Return -1 if second largest doesn't exist
}
int main() {
int array[] = {12, 35, 1, 10, 34, 1};
int n = sizeof(array) / sizeof(array[0]);
int result = findSecondLargest(array, n);
if (result != -1) {
printf("The second largest element is: %d\n", result);
} else {
printf("There is no second largest element.\n");
}
return 0;
}
Explanation
- Include Headers: The program starts by including the standard input-output header (
<stdio.h>
) and the limits header (<limits.h>
) for defining constants. - Function Definition: The function
findSecondLargest
takes an array and its size as arguments. It returns the second largest element or-1
if it doesn’t exist. - Edge Case Check: The function first checks if the size of the array is less than 2. If so, it returns
-1
, indicating there aren’t enough elements. - Initialization: Two variables,
first
andsecond
, are initialized to the smallest possible integer value (INT_MIN
). This allows for comparison with any number in the array. - Iteration: The function loops through the array:
- If the current element is greater than
first
, it updatessecond
to befirst
and setsfirst
to the current element. - If the current element is not larger than
first
but is larger thansecond
, it updatessecond
.
- If the current element is greater than
- Return Value: After the loop, if
second
is stillINT_MIN
, it means there was no valid second largest element, and the function returns-1
. Otherwise, it returns the value ofsecond
.
Output
For the input array {12, 35, 1, 10, 34, 1}
, the output will be:
csharpCopy codeThe second largest element is: 34
This implementation efficiently finds the second largest element in a single pass through the array, achieving O(n) time complexity.