In: Computer Science
Two examples of a correct execution of the program are shown below:
Enter the numbers in random order: (close by entering q) 34 254 1 -5 -13 q The second smallest number is -5
And:
Enter the numbers in random order: (close by entering q) 4 4 4 4 4 q error: no second smallest
Code using c++ only.
here is code:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int secondSmallestNumber(vector<int> &v); // function declaration
// main function to run program
int main() {
// prompt user to enter input data
cout << "Enter the numbers in random order:
(close by entering q)" << endl;
vector<int> v; // create a int vector object to
pass it as function parameter to secondSmallestNumber
function
int input; // declare variable to store use
input
stringstream ss; // create stringstream object to
convert string in to integers
string str; // variable to store user input as
string
bool flag = false; // create flag to indicate
noninteger value is encountered
while (!flag) {
getline(cin, str); // get string
input from user
ss.clear(); // clear the
stringstream for second input
ss << str; // pass string to
stringstream object
while (ss >> input ||
!ss.eof()) {
//while loop to
continue till error occurs converting integers of end of stream
occurs;
//check if error
ouccurs in parsing
if (ss.fail())
{
flag = true; // set flaf to true
break; // break the inner while loop
}
v.push_back(input); // add integer to end of vector
}//end of inner while loop
}//end of outer while loop
int result; // variable to store secondsmallest
number
//try getting result value from seconsmallestnumber
function
//if exception is thrown, print error message
try {
result =
secondSmallestNumber(v);
cout << "The second smallest
number is " << result << endl; // print result
}
catch (const exception& e) {
cout << "error: no second
smallest" << endl;
}
return 0;
}
// function implimentation
int secondSmallestNumber(vector<int> &v)
throw(...){
//sort the vector ,complexity is exluded for sorting
algorithms
std::sort(v.begin(), v.end());
int number = v.at(0); // get first element in vector
as smallest number
//loop the vector for second smallest number
for (int i = 0; i < v.size() - 1; i++) {
// check for second smallest
number
if (v.at(i + 1) > number) { //
comparing i+1 as the first element is already taken for
comprison
// if number
found return the number
return v.at(i +
1);
}
}
// if number not found then throw exception
throw exception("error");
//this is linear search so worst case complexity is
number not found
//eg. O(n);
}