Understanding Recursion with Simple Examples
Q: What is recursion, and can you provide a simple example of a recursive function?
- Data Structures And Algorithms
- Junior level question
Explore all the latest Data Structures And Algorithms interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Data Structures And Algorithms interview for FREE!
Recursion is a programming technique where a function calls itself in order to solve a problem. This method is often used to break down complex problems into simpler ones. A recursive function typically has two main components: a base case that stops the recursion and a recursive case that continues the process.
A classic example of a recursive function is the calculation of the factorial of a non-negative integer. The factorial of a number \( n \) (denoted as \( n! \)) is the product of all positive integers less than or equal to \( n \). The mathematical definition can be expressed recursively as follows:
- \( n! = n \times (n-1)! \) for \( n > 0 \)
- \( 0! = 1 \) (the base case)
Here is a simple implementation in Python:
```python
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120
```
In this example, when `factorial(5)` is called, it calculates \( 5 \times factorial(4) \), which in turn calculates \( 4 \times factorial(3) \), and so on, until it reaches the base case with `factorial(0)`, returning 1. Then, the results are multiplied together as the function returns back up the call stack, resulting in the final output of 120.
A classic example of a recursive function is the calculation of the factorial of a non-negative integer. The factorial of a number \( n \) (denoted as \( n! \)) is the product of all positive integers less than or equal to \( n \). The mathematical definition can be expressed recursively as follows:
- \( n! = n \times (n-1)! \) for \( n > 0 \)
- \( 0! = 1 \) (the base case)
Here is a simple implementation in Python:
```python
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120
```
In this example, when `factorial(5)` is called, it calculates \( 5 \times factorial(4) \), which in turn calculates \( 4 \times factorial(3) \), and so on, until it reaches the base case with `factorial(0)`, returning 1. Then, the results are multiplied together as the function returns back up the call stack, resulting in the final output of 120.


