- How to find the second largest element in an array
- How to handle arrays with duplicate elements
- How to handle arrays with less than 2 elements
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to find the second largest element in an array.
Finding the second largest element is a common programming problem that tests your understanding of array traversal and comparison logic. It is used in many real-world applications, such as:
- Finding the second highest score in a class
- Finding the second highest salary in a company
- Finding the runner-up in a competition
- Finding the second highest temperature reading
š” Key Point: To find the second largest element, we keep track of the largest and second largest elements while traversing the array. When we find a new largest, the old largest becomes the second largest.
C Program to Find Second Largest Element in Array
#include <stdio.h>
int main() {
int n, i;
int largest, second_largest;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Check if array has at least 2 elements
if(n < 2) {
printf("\nArray must have at least 2 elements.\n");
return 1;
}
// Declare array
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Initialize largest and second largest
largest = arr[0];
second_largest = -1; // Use -1 or a very small number
// Find second largest
for(i = 1; i < n; i++) {
if(arr[i] > largest) {
second_largest = largest;
largest = arr[i];
}
else if(arr[i] > second_largest && arr[i] != largest) {
second_largest = arr[i];
}
}
// Display result
if(second_largest == -1) {
printf("\nNo second largest element found.\n");
} else {
printf("\nLargest element: %d\n", largest);
printf("Second largest element: %d\n", second_largest);
}
return 0;
}
Sample Output
Enter the number of elements: 6 Enter 6 elements: 50 20 40 10 30 60 Largest element: 60 Second largest element: 50
Example with Duplicate Elements:
Enter the number of elements: 7 Enter 7 elements: 50 50 40 10 30 60 60 Largest element: 60 Second largest element: 50
When All Elements are Same:
Enter the number of elements: 5 Enter 5 elements: 10 10 10 10 10 Largest element: 10 No second largest element found.
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;ā number of elementsint i;ā loop counterint largest;ā stores the largest elementint second_largest;ā stores the second largest element
- Validate Input: Checks if the array has at least 2 elements. If not, displays an error message.
- Initialize Variables:
largest = arr[0];ā assumes the first element is the largestsecond_largest = -1;ā initialized to a value that won't conflict
- Find Second Largest: The loop traverses from index 1 to n-1:
- If
arr[i] > largest:- Old largest becomes second largest
- New element becomes largest
- Else If
arr[i] > second_largest && arr[i] != largest:- Update second largest
- Skip duplicates of the largest element
- If
- Display Result: Prints the largest and second largest elements.
- Return:
return 0;indicates successful program execution.
š Note: The condition arr[i] != largest ensures that duplicate values of the largest element are not considered as the second largest.
Algorithm to Find Second Largest Element
Step-by-step algorithm:
- Start
- Read the array elements
- If n < 2, print "Array must have at least 2 elements" and exit
- Set
largest = arr[0] - Set
second_largest = -1 - For
i = 1ton-1:- If
arr[i] > largest:second_largest = largestlargest = arr[i]
- Else If
arr[i] > second_largest && arr[i] != largest:second_largest = arr[i]
- If
- If
second_largest == -1:- Print "No second largest element found"
- Else:
- Print largest and second largest
- End
Visual Example
Finding the second largest in the array [50, 20, 40, 10, 30, 60]:
Initialize: largest = 50, second_largest = -1
i=1: arr[1]=20 ā 20 < 50 and 20 > -1 ā second_largest = 20
i=2: arr[2]=40 ā 40 < 50 and 40 > 20 ā second_largest = 40
i=3: arr[3]=10 ā 10 < 40 ā no change
i=4: arr[4]=30 ā 30 < 40 ā no change
i=5: arr[5]=60 ā 60 > 50 ā second_largest = 50, largest = 60
Result: Largest = 60, Second Largest = 50
Alternative Method: Sorting Approach
Another approach is to sort the array and then find the second largest element. This is simpler but less efficient for large arrays.
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
if(n < 2) {
printf("\nArray must have at least 2 elements.\n");
return 1;
}
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort array in descending order (bubble sort)
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] < arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Find second largest (skip duplicates of largest)
int second_largest = -1;
for(i = 1; i < n; i++) {
if(arr[i] != arr[0]) {
second_largest = arr[i];
break;
}
}
printf("\nLargest element: %d\n", arr[0]);
if(second_largest != -1) {
printf("Second largest element: %d\n", second_largest);
} else {
printf("No second largest element found.\n");
}
return 0;
}
Time and Space Complexity
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Single Pass (Optimized) | O(n) | O(1) |
| Sorting Approach | O(n²) | O(1) |
š» Practice Exercise
Challenge 1: Modify the program to find the second smallest element in the array.
Challenge 2: Find the third largest element in the array.
š Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int n, i;
int smallest, second_smallest;
printf("Enter the number of elements: ");
scanf("%d", &n);
if(n < 2) {
printf("\nArray must have at least 2 elements.\n");
return 1;
}
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
smallest = arr[0];
second_smallest = 999999; // Large initial value
for(i = 1; i < n; i++) {
if(arr[i] < smallest) {
second_smallest = smallest;
smallest = arr[i];
}
else if(arr[i] < second_smallest && arr[i] != smallest) {
second_smallest = arr[i];
}
}
printf("\nSmallest element: %d\n", smallest);
if(second_smallest != 999999) {
printf("Second smallest element: %d\n", second_smallest);
} else {
printf("No second smallest element found.\n");
}
return 0;
}
Frequently Asked Questions
1. How do you find the second largest element in an array in C?
Traverse the array once, keeping track of the largest and second largest elements. When you find a new largest, the old largest becomes the second largest.
2. What if the array has duplicate elements?
Use the condition arr[i] != largest when updating the second largest. This ensures duplicates of the largest element are not counted as the second largest.
3. What is the time complexity of finding the second largest?
The optimal approach has a time complexity of O(n), where n is the number of elements. It requires only a single pass through the array.
4. What happens if all elements are the same?
If all elements are the same, there is no second largest element. The program will display "No second largest element found."
5. Can I use sorting to find the second largest element?
Yes, you can sort the array and then find the second largest. However, this is less efficient (O(n²) for bubble sort) and not recommended for large arrays.
š” Tip: Always initialize second_largest to a value that will be replaced by any valid element (like -1 or INT_MIN from limits.h).