Finding the second largest element in C/C++


#include<bits/stdc++.h>
using namespace std;
int second(int arr[], int s)
{
    int l1, l2;
    l1 = l2 = INT_MIN;
    for(int i = 0; i < s; i++){
        if(arr[i] > l1){
            l2 = l1;
            l1 = arr[i];
        }
        else if(arr[i] > l2 && l1 > arr[i]){
            l2 = arr[i];
        }
    }
    return l2;
}
int main()
{
    int n;
    cout<<"Enter the size of the array: ";
    cin>>n;
    int arr[n];
    cout<<"Enter the array elements: ";
    for(int i = 0; i < n; i++){
        cin>>arr[i];
    }
    int res = second(arr, n);
    cout<<"Second Largest is: "<<res<<endl;
    return 0;
}
 

1 comment: