Logic Building
def print_1_to_n(n):
# Base case
if n == 0:
return
# Recursive case: print smaller problem first
print_1_to_n(n - 1)
print(n)
# Test
n = int(input("Enter n: "))
print_1_to_n(n)Output
Enter n: 5 1 2 3 4 5
Recursively solve smaller problem, then print current number.
Key Concepts:
- Base case: n == 0, return
- Recursive case: print 1 to n-1, then print n
- Function calls itself with smaller value