⬅ Previous Topic
Variable Scope: Local, Global, and NonlocalNext Topic ⮕
Arrays⬅ Previous Topic
Variable Scope: Local, Global, and NonlocalNext Topic ⮕
ArraysRecursion is a programming concept where a function calls itself in order to solve a problem. It's commonly used to break down problems into smaller, more manageable parts.
function recursiveFunction(parameters):
if base_condition_met:
return base_result
else:
return recursiveFunction(modified_parameters)
Let’s start with a classic example — computing the factorial of a number. Factorial of n (written as n!) is the product of all positive integers less than or equal to n.
function factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Output:
factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
factorial(5)
calls factorial(4)
factorial(4)
calls factorial(3)
factorial(0)
returns 1 (base case)1 → 1×1 → 2 → 6 → 24 → 120
What would happen if we don’t define the base case?
The function would keep calling itself indefinitely, eventually leading to a stack overflow (i.e., the program will crash due to too many nested function calls).
This function calculates the sum of the first n
numbers using recursion.
function sum(n):
if n == 1:
return 1
else:
return n + sum(n - 1)
Output:
sum(5) = 5 + 4 + 3 + 2 + 1 = 15
Is recursion always better than iteration?
No. Recursion is elegant but can be inefficient due to memory overhead. Iterative solutions often use less memory. Choose recursion when it offers clearer logic or when the problem itself is recursive in nature (like trees).
Recursion is a powerful concept that teaches you how to think in terms of problem decomposition. It’s especially useful in problems involving repeated patterns or hierarchical structures. With practice, recursion becomes an intuitive and valuable tool in your programming skillset.
⬅ Previous Topic
Variable Scope: Local, Global, and NonlocalNext Topic ⮕
ArraysYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.