🔁 Recursion Debugging (Simple Explanation)
Recursion debugging means finding and fixing errors in a function that calls itself.
🧠 1. What happens in recursion?
Every recursive function must have:
- ✅ Base Case → stopping condition
- 🔁 Recursive Call → function calling itself
If something is wrong → program may:
- ❌ Run forever (infinite recursion)
- ❌ Give wrong output
- ❌ Crash (stack overflow)
🔍 2. Common Recursion Errors
❌ 1. Missing Base Case
def fact(n):
return n * fact(n-1)
👉 Problem: No stopping condition → infinite loop
❌ 2. Wrong Base Case
def fact(n):
if n == 0:
return 0 # ❌ wrong
return n * fact(n-1)
👉 Factorial of 0 should be 1, not 0
❌ 3. Wrong Recursive Call
def fact(n):
if n == 1:
return 1
return n * fact(n+1) # ❌ wrong direction
👉 It should reduce n, not increase
❌ 4. Stack Overflow (Too deep recursion)
def loop(n):
return loop(n+1)
👉 Never stops → crash
🧠 Code Understanding
def fact(i, a):
if i <= 5:
a = a * i
return fact(i + 1, a)
return a
print(fact(1, 1))
Meaning:
i → current number
a → accumulated result (answer store panra variable)
🔁 Step-by-Step Flow
📍 Initial Call
fact(1, 1)
🔽 Call Phase (Going Down)
i=1, a=1 → a = 1*1 = 1 → fact(2, 1)
i=2, a=1 → a = 1*2 = 2 → fact(3, 2)
i=3, a=2 → a = 2*3 = 6 → fact(4, 6)
i=4, a=6 → a = 6*4 = 24 → fact(5, 24)
i=5, a=24 → a = 24*5 = 120 → fact(6, 120)
🔼 Return Phase (Coming Back)
👉 Important:
This is tail recursion, so no pending calculations
fact(6,120) → 120
fact(5,24) → 120
fact(4,6) → 120
fact(3,2) → 120
fact(2,1) → 120
fact(1,1) → 120
🎯 Final Output
120
📊 Simple Flow Diagram
embed fact(1,1)
↓
fact(2,1)
↓
fact(3,2)
↓
fact(4,6)
↓
fact(5,24)
↓
fact(6,120) → return 120
Top comments (0)