Question

In: Computer Science

Take an unknown number of integers as input and print the second smallest number. If there...

  • Take an unknown number of integers as input and print the second smallest number.
  • If there is no second smallest number in the sequence the program should print an error message and quit.
  • Write a function that takes a vector as argument and that returns an int containing the second smallest number. If no such number exists, the function should throw an exception that in turn is caught in main.
  • Your program should compute its answer with a complexity no worse than O ( n ). Note that this requirement excludes, e.g., sorting the sequence of numbers.
    • The professor means to say: "Your program should compute its answer with a complexity no worse than O ( n ). Note that this requirement excludes, e.g., the use of sorting algorithms on the sequence of numbers."
  • The program should read integers from cin until something non-numeric is entered.

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.

Solutions

Expert Solution

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);
}


Related Solutions

write a method that returns the index of the second smallest element in an array of integers. If the number of such elements is greater than 1.
write a method that returns the index of the second smallest element in an array of integers. If the number of such elements is greater than 1. return the second smallest index. Use the following header:public static int index of seconds sma11eststenent tint array
Martin wants to create a program that requires the user to input 10 integers then print...
Martin wants to create a program that requires the user to input 10 integers then print the total number of even integers, highest even integer, lowest even integer, total number of odd integers, highest odd integer, and lowest odd integer. If, however, the user inputs zero (0), the program will display “You have not yet entered 10 integers.” Below is the sample output of the program Martin created. Enter the integers: Integer 1: 15 Integer 2: 9 Integer 3: 71...
Use C Programming - Given an array of integers and a number K, find the smallest...
Use C Programming - Given an array of integers and a number K, find the smallest element in array greater than or equal to K. If such element exists in the array, display it otherwise display "-1". Example: Input:     8     1 3 4 7 8 9 9 10     5     where: First line represents the number of elements in the array. Second line represents the elements in the array. Third line represents the value of K. Output:     7 Explanation:...
Question 1: 5pts Write a program to receive two integers as user input and then print:...
Question 1: 5pts Write a program to receive two integers as user input and then print: Sum Difference Product Average Maximum of the two Minimum of the two You may use the min and max functions declared in the math class. ********************************************************************************** Question 2: 10pts An online bank wants you to create a program that will show a prospective customer, how the deposit will grow. Your program should read the initial balance and the annual interest rate. Interest rate is...
Question 1: Write a program to receive two integers as user input and then print: Sum...
Question 1: Write a program to receive two integers as user input and then print: Sum Difference Product Average Maximum of the two Minimum of the two You may use the min and max functions declared in the math class. ********************************************************************************** Question 2: An online bank wants you to create a program that will show a prospective customer, how the deposit will grow. Your program should read the initial balance and the annual interest rate. Interest rate is compounded monthly....
Write a java program that will take a line of input and go through and print...
Write a java program that will take a line of input and go through and print out that line again with all the word numbers swapped with their corresponding numeric representations (only deal with numbers from one to nine). Sample runs might look like this: Please enter a line of input to process: My four Grandparents had five grandchildren My 4 grandparents had 5 grandchildren without array and methods.
Write a C++ program that reads integers from standard input until end of file. Print out...
Write a C++ program that reads integers from standard input until end of file. Print out the largest integer that you read in, on a line by itself. Any erroneous input (something that is not an integer) should be detected and ignored. In the case where no integers are provided at all, print NO INTEGERS and stop. The whole program is under 40 lines of code. Just read from cin. Now, you need to detect non integers. In this case,...
One dimensional dynamic array Write a function that returns the number of integers in an input...
One dimensional dynamic array Write a function that returns the number of integers in an input file stream with the following interface: int findNumber(ifstream &x); Then, use this number to dynamically allocate an integer array. Write another function that reads each number in an input file stream and assign the value to the corresponding array element with the following interface: void assignNumber(ifstream &x, int y[ ]); In your main( ), first open “in.dat” as an input file. Next, apply findNumber(...
a What is the size of the smallest sample required to estimate an unknown proportion of...
a What is the size of the smallest sample required to estimate an unknown proportion of customers who would pay for an additional service, to within a maximum error of 0.06 with at least 95% confidence?   1b With reference to the previous problem, how would the required sample size be affected if it is known that the proportion to be estimated is at least 0.75?
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b...
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b where a + b is equal to a given number. For example, consider the following array and suppose we want to find all pairs of integers a and b where a + b = 16 A= [ 10, 4, 6, 15, 3, 5, 1, 13] The following are pairs that sum to 16: 13, 3 6, 10 15, 1 Your program should print these...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT