BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C++ Program to Find Second Smallest Element in an Array

By Chaitanya Singh | Filed Under: C++ Programs

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.

To understand this program you should have the basic knowledge of if-else-if control statement, for loop, C++ array, user-defined functions

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

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”.

Try These Related Programs

  • C++ Program to find smallest element in an array
  • C++ Program to Find largest element in an array
  • C++ Program to find second largest element in an array
  • C++ Program to find the missing number in a sequential array

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap