Print N to 1 using Recursion
EasyPrint first, then recurse
Problem
Print numbers from N down to 1 using recursion.
Print n, then recurse for n-1 — the calls unwind from big to small.
The idea
Print n immediately and then hand n-1 to the next call, so the output comes out on the way down. Swapping these two lines flips the order entirely.
The trick
- Work-then-recurse prints descending; recurse-then-work prints ascending.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
5
0
Step 1 of 2. Here's the example — n = 5 Values: 5.
1/2
Optimal
timeO(n)spaceO(n)
1f(i):2 if i<1: return3 print(i)4 f(i-1)Input
- array
- [5]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 3
- Output:
- 3 2 1
- Explanation:
- Print n, then recurse downward.
Example 2
- Input:
- n = 5
- Output:
- 5 4 3 2 1
- Explanation:
- Counts down from 5.
Example 3
- Input:
- n = 1
- Output:
- 1
- Explanation:
- Just 1.
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.