Understanding Recursion in Layman's Terms
Recursion is a term used in programming to describe a process where a function calls
itself. It's a way of solving problems where the solution involves solving smaller
instances of the same problem.
Imagine you're standing in front of a mirror holding another mirror. What do you see?
An infinite number of reflections, right? Each reflection is a smaller version of the
one before it. This is very similar to how recursion works—solving a problem by
breaking it into smaller versions of itself.
How Does Recursion Work?
In recursion, a function solves a small part of the problem and then calls itself to
solve the rest. This process continues until a condition is met that stops the
recursion (called the base case). The base case prevents the recursion from going on
forever, just like you stop seeing more reflections when the mirrors can't reflect
anymore.
Key Parts of Recursion:
1. Base Case: The simplest version of the problem where recursion stops. Without
this, the function would call itself infinitely.
2. Recursive Case: The part of the function where it calls itself with a smaller
or simpler input.
Example: Factorial of a Number
The factorial of a number n is the product of all positive integers from 1 to n .
For example:
factorial(3) = 3 * 2 * 1 = 6
factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
Let's write a Python function to calculate the factorial of a number using recursion.
Factorial Example in Python
def factorial(n):
# Base case: if n is 1 or 0, return 1
if n == 1 or n == 0:
return 1
else:
# Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1)
# Test the function
print(factorial(5)) # Output: 120