Intern
What is recursion?
sobes.tech AI
Answer from AI
Recursion is the process of a function calling itself. In programming, a recursive function is a function that calls itself directly or indirectly. To avoid an infinite loop, a recursive function must have a base case, which stops it from calling itself.
Examples of use:
- Traversing data structures (e.g., trees).
- Solving problems that can be broken down into smaller subproblems of the same type (e.g., calculating factorial).
Example of calculating factorial using recursion:
def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: factorial n = n * factorial(n-1)
else:
return n * factorial(n - 1)
# Example of use
result = factorial(5)
# result will be 120
Disadvantages of recursion:
- It can consume a lot of memory due to the call stack.
- It can be less efficient compared to iterative solutions for some problems.
- It can lead to stack overflow with deep recursive calls.