C++

Finding The Second-Smallest Element In An Array Using A C++ Program

The user is prompted to enter the array’s size in this software (number of elements). The user would then be prompted to enter every element of the array. The for loop is then used to find the array’s second-smallest element.

You should have a basic understanding of the if-else-if control statement, the for loop, the C++ array, and user-defined functions in order to understand this program.

Finding the second-smallest element in an array using a program

#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
78
13
21
Second Smallest Element: 9

Explained: The first two elements of the array are being compared, with the smaller one being assigned to the “smallest” variable and the other to the “secondSmallest” variable. Every element in the array is compared to the smallest variable inside the loop; if any element is smaller than the “smallest” variable, the value of the “smallest” variable is copied to the “secondSmallest” variable, and the element is copied to the “smallest” variable.

If the array member is larger than “smallest,” we compare it to “secondSmallest” such that the secondSmallest is updated if it discovers any element larger than “smallest” but smaller than “secondSmallest,” in the else if section.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button