31,673 views
34 votes
34 votes
Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including the last one.Ex: If the input is:5 2 4 6 8 10the output is:10,8,6,4,2,To achieve the above, first read the integers into a vector. Then output the vector in reverse.

User Alan Zeino
by
2.6k points

1 Answer

19 votes
19 votes

Answer:

The program in C++ is as follows:

#include <iostream>

#include <vector>

using namespace std;

int main(){

vector<int> intVect;

int n;

cin>>n;

int intInp;

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

cin >> intInp;

intVect.push_back(intInp); }

for (int i = n-1; i >=0; i--) { cout << intVect[i] << " "; }

return 0;

}

Step-by-step explanation:

This declares the vector

vector<int> intVect;

This declares n as integer; which represents the number of inputs

int n;

This gets input for n

cin>>n;

This declares intInp as integer; it is used to get input to the vector

int intInp;

This iterates from 0 to n-1

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

This gets each input

cin >> intInp;

This passes the input to the vector

intVect.push_back(intInp); }

This iterates from n - 1 to 0; i.e. in reverse and printe the vector elements in reverse

for (int i = n-1; i >=0; i--) { cout << intVect[i] << " "; }

User Alkar
by
3.1k points