codescracker
c++

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



« C++ Tutorial C++ Example »

This article provides a program in C++ that find and prints the second smallest element from a given array. The first program is based on 10 array elements. Whereas the second program is based on n array elements.

Find Second Smallest Element using for Loop

The question is, write a C++ program that receives 10 array elements from user to find and print the second smallest element. Here is its answer:

#include<iostream>

using namespace std;
int main()
{
   int i, num[10], small, ssmall;
   cout<<"Enter any 10 elements for the array: ";
   for(i=0; i<10; i++)
      cin>>num[i];
   small = num[0];
   for(i=0; i<10; i++)
   {
      if(small>num[i])
         small = num[i];
   }
   ssmall = num[0];
   for(i=0; i<10; i++)
   {
      if(ssmall>num[i])
      {
         if(num[i]!=small)
            ssmall = num[i];
      }
   }
   cout<<"\nSecond smallest element = "<<ssmall;
   cout<<endl;
   return 0;
}

The snapshot given below shows the initial output produced by above C++ program on finding the second smallest element from an array:

c++ find second smallest element

Now supply the input say 10, 9, 1, 2, 8, 7, 3, 4, 5, 6 as 10 array elements and press ENTER key to find and print the second smallest from all given 10 elements for the array like shown in the snapshot given below:

find second smallest element c++ program

Allow User to Define the Size for Array

Since previous program is created with a limitation of only using 10 array elements, I've modified and created another program as given below, that find and prints the second smallest element from an array of n elements. The value of n and all n elements must be entered by user at run-time:

#include<iostream>

using namespace std;
int main()
{
   int tot, i, num[100], s, ss;
   cout<<"Enter the Size for Array (max.100): ";
   cin>>tot;
   cout<<"Enter any "<<tot<<" elements for the array: ";
   for(i=0; i<tot; i++)
      cin>>num[i];
   s = num[0];
   for(i=0; i<tot; i++)
   {
      if(s>num[i])
         s = num[i];
   }
   ss = num[0];
   for(i=0; i<tot; i++)
   {
      if(ss>num[i])
      {
         if(num[i]!=s)
            ss = num[i];
      }
   }
   cout<<"\nSecond smallest element = "<<ss;
   cout<<endl;
   return 0;
}

Here is its sample run with user input 6 as size and 1, 2, 3, 4, 5, 0 as six elements:

print second smallest element from array c++

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker