In: Computer Science
Why do we need to use a decrement operator to get it to write the numbers in reverse?
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 space, including the last one.
Ex: If the input is:
5 2 4 6 8 10
#include <iostream>
#include <vector> // Must include vector library to use
vectors
using namespace std;
int main() {
vector<int> userInts;
// A vector to hold the user's input integers
int i, n, num;
cin>>n;
for(i = 1; i <= n; i++){
cin>>num;
userInts.push_back(num);
}
for(i = userInts.size() - 1; i >= 0; i--)
cout<<userInts[i]<<" ";
cout<<endl;
return 0;
}
the output is:
10 8 6 4 2
To achieve the above, first read the integers into a vector. Then output the vector in reverse.
Please find below explanation for the code you mentioned. Don't forget to give a Like.
As your code is working fine to reverse the numbers that are entered by user.
Take an example
array1={5,6,7,8,9,10}
the position/index of 5 is 0,
the index of 6 is 1,
likewise, the index of last element 10 is 5.
Size of array/vector is 6 but the array index is starting from 0, the last element size will be array.size()-1.
Now, coming to decrement operator.
As you asked to write the reverse of array/vector.
Reverse in the sense last element which will be vector.size()-1 which will be 5 for my example
//starting from 5, next should be element at 4, next 3,2,1,0...Looks like decrement by 1
for(int i=5;i>=0;i--){
//we print the element using cout<<vector[i]; this prints the ith element first and will be decremented.
}
If we want to print elements in same order then we take increment operator because staring from 0 till we need to go last.
for(int i=0;i<=array.size()-1;i++)
{
cout<<array[i]
}
this prints array as it is..
Even we can use while loop to reverse array or vector.
i=array.size()-1
while(i>=0){
cout<<array[i];
i-=1;
}
first taking last element index in i and printing it and decrementing index by 1..
Likewise the reverse of vector or array will be printed.