Reverse with Recursion
Completed
Read n numbers using a recursive function that reads one number, recurses for the rest, and prints its number after the recursive call - so the numbers come out reversed.
Input
Line 1: n. Line 2: n integers.
Output
The numbers in reverse, one line.
Example
Input
5 1 2 3 4 5
Output
5 4 3 2 1
Editor
C
Hints
Each call keeps its own x on the call stack until it returns.
Solution explanation
The call stack stores every pending number, which is why the output comes out reversed.
Show solution
#include <stdio.h>
void read_and_print(int remaining) {
if (remaining == 0) return;
int x;
scanf("%d", &x);
read_and_print(remaining - 1);
printf("%d ", x);
}
int main() {
int n;
scanf("%d", &n);
read_and_print(n);
printf("\n");
return 0;
}