Understand recursion by print something N times
EasyA base case and one smaller call
Problem
Print a fixed message N times using recursion (no loops).
Do the action once, then recurse with one fewer — the base case stops the chain.
The idea
Print once, then ask the same function to handle the remaining n-1 prints, stopping when n reaches zero. Every recursive function is these two pieces: something that ends it, and a call on a strictly smaller problem.
The trick
- The base case must be reachable, or the stack overflows.
- Each call adds a stack frame, so depth n costs O(n) memory.
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 = 3, msg = 'Hi' Values: 3.
1f(i):2 if i>n: return3 print(msg)4 f(i+1)Input
- array
- [3]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- name = "Raj", n = 3
- Output:
- Raj Raj Raj
- Explanation:
- Print once, then recurse n-1 more times.
Example 2
- Input:
- name = "Ana", n = 1
- Output:
- Ana
- Explanation:
- A single print.
Example 3
- Input:
- name = "Bo", n = 2
- Output:
- Bo Bo
- Explanation:
- Twice.
Finished the walkthrough? Add it to your streak.