Second Largest, Second Smallest Write a program second.cpp that takes in a sequence of integers, and prints the second largest number and the second smallest number. Note that in the case of repeated numbers, we really mean the second largest and smallest out of the distinct numbers (as seen in the examples below). You may only use the headers: and . Please have the output formatted exactly like the following examples: (the red is user input) Enter integers (Q to quit): 1 2 1 8 8 9 Q Second largest: 8 Second smallest: 2 Enter integers (Q to quit): -7 -101 0 -2 17 Q Second largest: 0 Second smallest: -7

Respuesta :

Answer:

The program in C++ is as follows:

#include <vector>

#include <iostream>

using namespace std;

int main(){

   vector <int> my_num;

   string sentinel;

   int n = 0;

   cout<<"Enter integers (Q to quit): ";

   cin>>sentinel;

   while(sentinel != "Q"){

       my_num.push_back(stoi(sentinel));

       n++;

       cin>>sentinel;    }

      int n1, n2;

      n1 = my_num.at(0);      n2 = my_num.at(1);

      if(my_num.at(0)<my_num.at(1)){     n1 = my_num.at(1);  n2 = my_num.at(0);   }

      for (int i = 2; i< n ; i ++) {

          if (my_num.at(i) > n1) {

              n2 = n1;

              n1 = my_num.at(i);     }

           else if (my_num.at(i) > n2 && my_num.at(i) != n1) {

               n2 = my_num.at(i);     }  }

       cout<<"Second Largest: "<<n2<<endl;

       n1 = my_num.at(1);       n2 = my_num.at(0);

       if(my_num.at(0)<my_num.at(1)){ n1 = my_num.at(0);  n2 = my_num.at(1);   }

       for(int i=0; i<n; i++) {

           if(n1>my_num.at(i)) {  

               n2 = n1;

               n1 = my_num.at(i);            }

           else if(my_num.at(i) < n2){

               n2 = my_num.at(i);     }  }

 cout<<"Second Smallest: "<<n2;

 return 0;

}

Explanation:

See attachment for explanation

Ver imagen MrRoyal
ACCESS MORE
EDU ACCESS