In this article, we will write a C program to find the second largest number in an array. The program takes the elements of the array from the user as input, finds the second largest number and prints the result on the output window.
Sample Example:
Input:
Enter the size of the array: 5
Enter the elements of the array: 10 2 45 7 63
Output:
Largest = 63
Second Largest = 45
To find the second largest number in an array there are actually two approaches that are generally used. First, sort the array in the ascending order, after sorting, the second last element of the array will be the second largest element in the array.
At first glance, this approach might look like a good choice. But actually, it is not very efficient. That’s because you have to first sort the array which can have a time complexity of O(n2) in worst cases. We do not recommend this approach.
We can in fact find the second largest and even the largest element in the array with a time complexity of O(n).
Here is the algorithm that we can use to find the second largest number in an array:
- Consider two variables
largest
andsecond_largest
. - Assign the value of the first element of the array to both variables
largest
andsecond_largest
. Initially assume that the first element of the array is the largest. - Run a for/while loop over the array and check if the current element of the array is greater than the value stored in the
largest
variable. - If yes, store the current value of the
largest
variable in thesecond_largest
variable and store the value of the current element in thelargest
variable. - If not, check if the current element of the array is greater than the
second_largest
and less than thelargest
. - If yes, store the value of the current element in the
second_largest
.
Let’s put all the steps together and write a C program that finds the largest and second largest element in an array:
// C program to find the second largest number in an array #include <stdio.h> int main() { int arr[100], size; int largest, second_largest; printf("Enter the size of the array: "); scanf("%d", &size); printf("Enter the elements of the array: "); for (int i = 0; i < size; i++) { scanf("%d", &arr[i]); } // Assume that the first element is the second largest largest = second_largest = arr[0]; for (int i = 0; i < size; i++) { if (arr[i] > largest) { second_largest = largest; largest = arr[i]; } else if (arr[i] > second_largest && arr[i] < largest) { second_largest = arr[i]; } } printf("Largest = %d\n", largest); printf("Second Largest = %d", second_largest); return 0; }
Output:
Enter the size of the array: 5 Enter the elements of the array: 10 2 45 7 63 Largest = 63 Second Largest = 45
I hope you will find this article helpful. Thanks for reading.