4.0 Lecture 3 Recursion
4.0 Lecture 3 Recursion
4.0 Lecture 3 Recursion
1 Introduction to Recursion
Definition: Recursion is a method of solving a problem where the solution involves solving smaller
instances of the same problem. A recursive function is a function that calls itself in order to solve a
problem.
Key Concepts:
Base Case: The condition under which the recursive function stops calling itself. It is the simplest
instance of the problem that can be solved directly.
Recursive Case: The part of the function where the function calls itself with a smaller or simpler
version of the original problem.
1
function Fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
Simplifies the code for problems that have a natural recursive structure, such as tree traversals or
combinatorial problems.
Disadvantages:
Recursive functions can be less efficient in terms of memory usage due to the overhead of multiple
function calls.
Without a proper base case, a recursive function can lead to infinite loops and stack overflow errors.
4 Examples in Programming
Example 1: Sum of Array Elements
A recursive function to find the sum of an array of numbers:
2
5 Homework/Practice Problems
1. Write a recursive function to calculate the greatest common divisor (GCD) of two numbers using
Euclid’s algorithm.
2. Implement a recursive function to compute the sum of the digits of a given number.
4. Implement a recursive function to solve the Tower of Hanoi problem with 3 disks.
6 Conclusion
Recursion is a powerful tool in programming that helps to solve complex problems by breaking them down
into simpler subproblems. Understanding how to use recursion effectively is essential for solving problems
with a recursive structure.