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 .

Respuesta :

Answer:

The program is as follows:

#include <iostream>

#include <vector>

using namespace std;

int main(){

   int n;

   cout<<"Elements: ";

   cin>>n;

   vector <int>vectnum;

   int numInp;

   for (int i = 1; i <= n; i++){        cin>>numInp;        vectnum.push_back(numInp);    }

   int big, secbig;

   big = vectnum.at(0);      secbig = vectnum.at(1);

   if(vectnum.at(0)<vectnum.at(1)){     big = vectnum.at(1);  secbig = vectnum.at(0);   }

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

     if (vectnum.at(i) > big) {

        secbig = big;;

        big = vectnum.at(i);

     }

     else if (vectnum.at(i) > secbig && vectnum.at(i) != big) {

        secbig = vectnum.at(i);

     }

  }

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

  int small, secsmall;

  small = vectnum.at(1);       secsmall = vectnum.at(0);

  if(vectnum.at(0)<vectnum.at(1)){ small = vectnum.at(0);  secsmall = vectnum.at(1);   }

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

     if(small>vectnum.at(i)) {  

        secsmall = small;

        small = vectnum.at(i);      }

     else if(vectnum.at(i) < secsmall){

        secsmall = vectnum.at(i);      }   }

  cout<<"Second Smallest: "<<secsmall;

  return 0;

}

Explanation:

See attachment for explanation

Ver imagen MrRoyal
ACCESS MORE
EDU ACCESS