
Recursion is a process where a function or algorithm calls itself directly or indirectly to solve a problem by breaking it into smaller, self-similar subproblems.
Recursion is a process where a function or algorithm calls itself directly or indirectly to solve a problem by breaking it into smaller, self-similar subproblems.
Example (Factorial Function):
with base case .
Mathematical Recursion:
Programming Recursion:
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
Direct Recursion:
Indirect Recursion:
def is_even(n):
if n == 0: return True
else: return is_odd(n - 1)
def is_odd(n):
if n == 0: return False
else: return is_even(n - 1)
Tail Recursion:
def factorial(n, accumulator=1):
if n == 0: return accumulator
else: return factorial(n - 1, n * accumulator)
Tree Recursion:
A recurrence relation defines a sequence recursively (e.g., ).
Example (Merge Sort Recurrence):
Solution: (Master Theorem Case 2).
for, while).Example (Fibonacci Iterative vs. Recursive):
# Recursive (O(2^n) time)
def fib(n):
if n <= 1: return n
else: return fib(n-1) + fib(n-2)
# Iterative (O(n) time)
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
Recursion is a fundamental concept bridging mathematics and computer science, enabling elegant solutions to problems with repetitive substructures. Mastery requires understanding base cases, termination, and optimization techniques (e.g., memoization, tail recursion). While powerful, it must be used judiciously to avoid inefficiency or stack overflows.
Open this section to view and download past papers
Click on Show Past Papers to load available exam papers.