Recursion in programming is a technique where a function calls itself to solve a problem. It typically involves two main components:
Base Case: This is the condition under which the recursion stops. It prevents infinite loops by providing a simple case that can be solved directly.
Recursive Case: This is where the function calls itself with a modified argument, gradually working towards the base case.
Example: Factorial Calculation
Here's a simple example in Python to calculate the factorial of a number using recursion:
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:
- The base case is when
nis 0, returning 1. - The recursive case multiplies
nby the factorial ofn - 1.
Recursion is useful for problems that can be broken down into smaller, similar problems, such as tree traversals, searching algorithms, and more.
