Print 1 to N using Recursion
EasyRecurse first, print on the way back
Problem
Print numbers from 1 to N in increasing order using recursion.
Print the current number, then call yourself for the next — stopping when you pass n.
The idea
Call yourself on n-1 before printing n, so the deepest call — holding 1 — prints first and the stack unwinds in increasing order. This is the cleanest demonstration that a recursion has two phases.
The trick
- Print after the recursive call to get increasing order.
- Printing before it gives N down to 1 instead.
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.
Step 1 of 2. Here's the example — n = 5 Values: 5.
1f(i):2 if i>n: 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:
- 1 2 3
- Explanation:
- Print 1, then recurse for the rest up to n.
Example 2
- Input:
- n = 5
- Output:
- 1 2 3 4 5
- Explanation:
- Counts up to 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.