Wednesday, 22 November 2017

C++ Program to Find Second Smallest of n Elements with Given Complexity Constraint


Code:

#include    iostream

using namespace std;

// A function to calculate second.
int SecondSmallest(int *a, int n)
{
int s, ss, i;
// A variable 's' keeping track of smallest number.
s = a[0];
// A variable 'ss' keeping track of second smallest number.
ss = a[0];

// Traverse the data array.
for(i = 1; i < n; i++)
{
// If array element is lesser than current 's' value then update.
if(s > a[i])
{
ss = s;
s =  a[i];
}
// Otherwise the number can be second smallest number so check for the condition and update 'ss'.
else if(ss > a[i])
{
ss = a[i];
}
}
// Return second smallest number.
return ss;
}

int main()
{
int n, i;
cout<<"Enter the number of element in dataset: ";
cin>>n;

int a[n];
// Take input.
for(i = 0; i < n; i++)
{
cout<<"Enter "<
cin>>a[i];
}

// Print the result.
cout<<"\n\nThe second Smallest number of the given data array is: "<

return 0;
}


Output:

Enter the number of element in dataset:10

Enter 1th element: 23
Enter 2th element: 69
Enter 3th element: 586
Enter 4th element: 241
Enter 5th element: 329
Enter 6th element: 223
Enter 7th element: 652
Enter 8th element: 9
Enter 9th element: 121
Enter 10th element: 16

The second Smallest number of the given data array is: 16



More C++ Programs:














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...