This is my code below. It outputs correctly for the example given above. However
ID: 3845315 • Letter: T
Question
This is my code below. It outputs correctly for the example given above. However, the program will test with different lengths of vectors and that is where I am having trouble. Any help would be greatly appreciated.
#include <iostream>
#include <vector> // Must include vector library to use vectors
using namespace std;
int main() {
const int NUM_INPUT = 6;
vector<int> userInts(NUM_INPUT); // A vector to hold the user's input integers
unsigned int i;
/* Type your code here. */
for (i = 0; i < NUM_INPUT ; ++i) {
cin >> userInts.at(i) ;
}
for (i = NUM_INPUT-1 ; i > 0; --i) {
cout << userInts.at(i) << " ";
}
cout << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <vector> // Must include vector library to use vectors
using namespace std;
int main() {
//const int NUM_INPUT = 6; //This is not needed.
vector<int> userInts; // A vector to hold the user's input integers
int i, n, num; //Declaring supporting variables
/* Type your code here. */
cin>>n; //Reading length of vector
for (i = 0; i < n ; ++i) {
cin >> num; //Reading next integer
userInts.push_back(num); //Pushing integer into the vectot
}
//Displaying in reverse
for (i = n - 1 ; i >= 0; --i) {
cout << userInts.at(i) << " ";
}
cout << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.