C++ program to print second smallest element of the array


C++ program to print second smallest element of the array

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


Consider this example

array size = 5

elements = 5 3 4 1 2

elements after sorting = 1 2 3 4 5


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


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);             //sorting the array

    

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

    

    cout<<"Second smallest element is: "<<small;   //printing the 2nd smallest element


    return 0;

}


Input

5

4 7 9 3 1


Output

Second smallest element is: 3

Post a Comment

0 Comments