C++ Program to find the second smallest element in an array
October 13, 2021
Second smallest element in an array
An array is a group of similar type of data that are addressed by an common name (Arr[]). Array of any type can be created and may have one or more dimensions, i.e. 1-D Array, 2-D Array etc. Here we will learn how to code a C++ program for finding second smallest element in an array.
Algorithm :
Take the size of the array from the user and store it in variable say n.
Declare an array of n size and take n input elements for the array from the user.
Now , Declare two variable say min1 and min2.
Initialize them min1 as INT_MAX and min2 as INT_MAX-1
Iterate from i=0 to i=n-1 and check if the min1 >a[i] then update min2=min1 and min1 = a[i].
Else If min2 > a[i], then update min2 as min2 = a[i].
C++ code based on above algorithm
#include <iostream> using namespace std; int main(){
#include
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i>a[i];
}
for(int i=0;i<n-1;i++){
for(int j=i+1;ja[j]){
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
for(int i=0;i<n;i++){
if(i==1){
cout<<a[i]<<" ";
break;
}
}
return 0;
}