Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find the second smallest number of an array

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to find the second smallest number of an array

Objective

Write a C++ program to find the second smallest element of an array.

Algorithm / Approach

  1. Find the absolute smallest element (min) and save its exact index position in m.
  2. Initialize the second smallest smin to an element at the opposite end of the array.
  3. Loop through the array again to find the minimum value, BUT completely ignore the element at index m (if smin > a[i] && m != i).
  4. Print smin.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int m = 0, a[5],min,smin ;
 cout<<"Enter 5 Elements : ";
 for(int i =0; i< 5; i++) {
  cin>>a[i];
 }
 min = a[0];
 for(int i =1; i< 5; i++) {
  if(a[i] < min) {
   min = a[i];
   m = i;
  }
  }
 smin = a[5-m-1];
 for(int i =0 ; i< 5; i++) {
  if(smin> a[i] && m!= i) {
   smin = a[i];
  }
 }
 cout<<"Second Min = "<< smin;
return 0;
}

Expected Output

Enter 5 Elements : 1 3 45 32 54
Second Min = 3

Explanation of the Program

  • To find the second smallest, we first find the absolute smallest and record its index.
  • During our second pass through the array, we explicitly tell our if statement to skip that specific index. This forces the algorithm to find the smallest of the *remaining* numbers.

Complexity

Time Complexity O(n) - Two separate O(n) passes.
Space Complexity O(n)
ADVERTISEMENT