C++ Recursion
π C++ Recursion
Recursion is a technique where a function calls itself to solve a problem by breaking it into smaller subproblems.
Every recursive function must have:
-
Base case β stops recursion
-
Recursive case β calls itself with a smaller input
πΉ 1. Basic Syntax
πΉ 2. Simple Example (Print Numbers)
Output:
πΉ 3. Factorial Using Recursion
Output:
πΉ 4. Fibonacci Series (Recursive)
Output:
πΉ 5. Sum of Digits Using Recursion
Output:
πΉ 6. Reverse a Number (Recursive)
πΉ 7. Recursion vs Loop
| Recursion | Loop |
|---|---|
| Function calls itself | Repeats using iteration |
| Uses stack memory | Uses less memory |
| Cleaner for problems like trees | Faster for simple repetition |
| Risk of stack overflow | No stack overflow |
πΉ 8. Common Mistakes β
β Missing Base Case
β‘ Causes stack overflow
β Wrong Base Condition
πΉ 9. Tail Recursion
Recursive call is the last statement.
β Easier to optimize
β Similar to loops
πΉ 10. When to Use Recursion
-
Tree and graph traversal
-
Divide and conquer algorithms
-
Problems with repetitive structure
-
Mathematical definitions (factorial, Fibonacci)
π Summary
-
Recursion = function calling itself
-
Must have a base case
-
Solves problems by reducing size
-
Elegant but uses more memory
-
Avoid deep recursion if possible
