C++ program to print second largest element in array


C++ program to print second largest element in array

        In this program, you need to print the second largest element of the given array. For that, first sort the array in descending order. When the array is sorted in descending order the second largest element will be at the 1st index position. Print the 1st index position element.


Consider the example

array size = 5

elements = 2 3 5 1 4


elements after sorting = 5 4 3 2 1


Thus you will print the 1st index position element that is 4.


Code

#include <bits/stdc++.h>

using namespace std;


int main()

{

    int n;                              //array size

    cin>>n;

    

    int a[n];                       //array declaration

    

    for(int i=0;i<n;i++){           //reading array

        cin>>a[i];

    }

    

    sort(a,a+n,greater<int>());             //sorting array in descending order

    

    int large=a[1];                 //the second largest element is at 1st index hence storing it in large

    

    cout<<"Second largest element is: "<<large;                   //printing 2nd largest element


    return 0;

}


Input

5

4 7 9 3 1


Output

Second largest element is: 7


Post a Comment

0 Comments