📌 Recursion: Principles of Recursion
1️⃣ What is Recursion?
Recursion is a programming technique where a function calls itself to solve a problem. It breaks a problem into smaller subproblems until it reaches a base condition.
Example: Factorial Using Recursion
🔹 Output:
2️⃣ Principles of Recursion
(a) Base Case (Termination Condition)
A base case is the condition where recursion stops. Without it, recursion runs infinitely, causing a stack overflow.
🔹 Example: In the factorial function, the base case is:
(b) Recursive Case (Self-Call with Reduced Problem Size)
Each recursive call reduces the problem size and moves toward the base case.
(c) Stack Memory Usage
Each recursive call stores its state in the call stack. When the base case is reached, calls start returning results.
🔹 Example: Recursive Stack for factorial(5)
Each function call waits for the next call to return its value.
3️⃣ Types of Recursion
(a) Direct Recursion
A function calls itself directly.
(b) Indirect Recursion
A function calls another function, which calls it back.
(c) Tail Recursion
The recursive call is the last operation before returning.
🔹 More memory-efficient than normal recursion.
4️⃣ Common Recursion Problems
(a) Fibonacci Series
(b) Sum of Digits
(c) Reverse a String
5️⃣ Recursion vs Iteration
Aspect | Recursion | Iteration |
---|---|---|
Memory Usage | High (Stack) | Low |
Speed | Slower (Function Calls) | Faster |
Code Simplicity | More Elegant | More Efficient |
Example | Factorial using recursion | Factorial using loop |
6️⃣ When to Use Recursion?
✅ Problems with natural recursive structure (Trees, DFS, Fibonacci).
✅ When code clarity is more important than performance.
✅ When stack space is not a constraint.
🚀 Do you prefer recursion or loops? Let’s discuss! ⬇️
No comments:
Post a Comment