Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print 1 to N Recursively

Print one through n with recursive calls. Students trace a zero base case, pending calls, and why printing after the recursive call reverses the return order.

IntermediatePhase 3 - Level 1: Basic RecursionExample 1 of 10
print-1-to-n-recursively.py
1def print_1_to_n(n):
2 # Base case
3 if n == 0:
4 return
5
6 # Recursive case: print smaller problem first
7 print_1_to_n(n - 1)
8 print(n)
9
10# Test
11n = int(input("Enter n: "))
12print_1_to_n(n)

Output

Enter n: 5
1
2
3
4
5

In this one

  • Define a recursion base case
  • Trace waiting calls
  • Print during return

How it works

  1. 1

    Return immediately at n equal to zero.

  2. 2

    Call print_1_to_n with n - 1.

  3. 3

    After it returns, print the current n.

Edge cases

What does n = 0 print?

What does n = 0 print?

Nothing; the base case returns immediately.

What about negative n?

What about negative n?

It never reaches this base case and eventually raises RecursionError.

What's going on

The function first calls itself with n - 1, postponing print(n). At zero it returns without printing.

The call stack records the waiting calls. As they resume, one prints before two, then three. A base case is essential: negative inputs keep decreasing away from zero, and sufficiently deep calls raise RecursionError.

What does n = 0 print? Nothing; the base case returns immediately.

What about negative n? It never reaches this base case and eventually raises RecursionError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why is the output ascending?

Pick an answer to check it.

Question 2

What does n = 0 print?

Pick an answer to check it.

Questions people ask

What does n = 0 print?

Nothing; the base case returns immediately.

What about negative n?

It never reaches this base case and eventually raises RecursionError.

Why is the output ascending?

Printing happens after the smaller call returns.