In this tutorial, we will see how to find the second largest element in an array. There are different ways to do it- like sorting the array first in descending order and then printing the second element or by double iteration- first for finding the largest element and second for finding the number just less than the largest. But there is one way to find the second largest element just in single iteration. Here is the code for the program.
Output: The second largest element is 8.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<climits> | |
using namespace std; | |
int secondLargest(int arr[], int n) { | |
int first = INT_MIN; | |
int second = INT_MIN; | |
for(int i = 0; i<n; i++) { | |
if(arr[i]>first) { | |
second = first; | |
first = arr[i]; | |
} | |
if(arr[i]<first && arr[i]>second) { | |
second = arr[i]; | |
} | |
} | |
return second; | |
} | |
int main() { | |
int arr[] = {8,5,6,8,3,4,9,1,2}; | |
int n = sizeof(arr) / sizeof(arr[0]); | |
cout<<"The second largest element is "<<secondLargest(arr, n); | |
return 0; | |
} |
No comments:
Post a Comment