Find Second Smallest Number using Array in C++


This is a C++ program that finds the second smallest element in an array of integers. The program first prompts the user to enter the size of the array, and then initializes an integer array of that size, called arr. It then prompts the user to enter the elements of the array one by one, which are stored in arr.

Next, the program calls a function called findSecondSmallest, which takes in the array arr and its size n as parameters. Inside the function, the program initializes two variables smallest and secondSmallest to the first and second elements of the array respectively. It then loops through the remaining elements of the array using a for loop and compares each element with the current values of smallest and secondSmallest. If the element is smaller than smallest, the program updates the values of smallest and secondSmallest accordingly. If the element is not smaller than smallest but smaller than secondSmallest, the program updates the value of secondSmallest to that element.

Finally, the function returns the value of secondSmallest, which is then outputted by the main function..

Source Code

#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<<"\nEnter the size of array: ";
  cin>>n;
  int arr[n-1];
  cout<<"\nEnter array elements: ";
  for(int i=0;i<n;i++)
  {
      cin>>arr[i];
  }
  int secondSmallest=findSecondSmallest(arr,n);
  cout<<"\nSecond Smallest Element: "<<secondSmallest;
  return 0;
}
To download raw file Click Here

Output

Enter the size of array: 5
Enter array elements: 11
12
13
14
15
Second Smallest Element: 11

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples