FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Second Smallest Element in an Array

noidatut course




In this program we ask the user to enter the size of array (number of elements). Then user would be asked to enter all the elements of array. The program then finds the second smallest element of the array using for loop.

Program to find second smallest element in an array

#include <iostream>  
using namespace std;  
int findSecondSmallest(int arr[], int n){
     int smallest, secondSmallest;
     if(arr[0]<arr[1]){
        smallest = arr[0];
        secondSmallest = arr[1];
     }     else {
        smallest = arr[1];
        secondSmallest = arr[0];
     }
     for(int i=0; i<n; i++) {
        if(smallest>arr[i]) {
            secondSmallest = smallest;
           smallest = arr[i];
        }
        else if(arr[i] < secondSmallest){
           secondSmallest = arr[i];
        }     }
     return secondSmallest;
  }
  int main()
 {
     int n;
     cout<<"Enter the size of array: ";
     cin>>n;
     int arr[n-1];
     cout<<"Enter array elements: ";
     for(int i=0; i<n; i++){
        cin>>arr[i];
     }
      int secondSmallest = findSecondSmallest(arr, n);
     cout<<"Second Smallest Element: "<<secondSmallest;
     return 0;
  }

Output

Enter the size of array: 5
Enter array elements: 11
9
18
88
101
Smallest Element is: 11

Explanation:

Explanation: We are comparing the first two element of array and assigning the smaller between them to the "smallest" variable and the other to "secondSmallest" variable. Inside loop we are comparing the smallest variable with every element of array, if any element is smaller than “smallest” variable then we are copying the value of "smallest" variable to "secondSmallest" and copying the element to "smallest".

else if part: If the the array element is greater than “smallest” then we are comparing it with “secondSmallest” so that the secondSmallest gets updated if it finds any element greater than “smallest” but less than “secondSmallest”.







Leave Comment