Recursion is a programming 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.
- Recursive Case: This is where the function calls itself with a modified argument, gradually approaching the base case.
Example:
Here's a simple example in Python that calculates the factorial of a number:
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
In this example, factorial calls itself with n - 1 until it reaches the base case of n == 0.
