Recursion Presentation
Recursion Presentation
Simple
A guide to mastering the concept
with examples
Introduction to Recursion
• Definition:
• Recursion is a method where the solution to a
problem depends on solving smaller instances
of the same problem.
• Key Feature:
• A function calls itself.
Recursion vs. Iteration
• Recursion:
• - Uses function calls.
• - Simplifies problems.
• Iteration:
• - Uses loops (for, while).
• - More memory-efficient.
Anatomy of a Recursive Function
• 1. Base Case: Stops recursion.
• 2. Recursive Case: Calls itself with smaller
input.
Example 1 - Factorial
• def factorial(n):
• if n == 0: # Base Case
• return 1
• else: # Recursive Case
• return n * factorial(n - 1)
• print(fibonacci(5)) # Output: 5
Visualization of Fibonacci
• Tree structure showing calls to fibonacci(4)
and fibonacci(3)
Importance of Base Case
• Without a base case, recursion leads to
infinite loops and stack overflow errors.
• Example:
• def infinite_recursion():
• infinite_recursion()
• Cons:
• - Higher memory usage.
• - Risk of stack overflow.
Tips for Writing Recursive
Functions
• 1. Clearly define the base case.
• 2. Ensure progress towards the base case.
• 3. Visualize the problem (e.g., recursion tree).
• 4. Use memoization for efficiency (dynamic
programming).
Conclusion
• Recursion is a powerful tool for problem-
solving.
• Practice is key to mastering it.
• Questions?