Challenge: Print Backwards
Completed
Read n and then n numbers. Print the numbers in reverse order on one line, separated by spaces.
Input
n, then n integers.
Output
The numbers from last to first, separated by single spaces.
Example
Input
5 1 2 3 4 5
Output
5 4 3 2 1
Editor
C++
Hints
Store the numbers in a vector first.
Loop from index n - 1 down to 0.
Solution explanation
You can't print backwards until you've read everything, so the vector stores the numbers first.
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
for (int i = n - 1; i >= 0; i--) {
cout << v[i];
if (i > 0) cout << " ";
}
cout << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module