Junior — Middle
What is recursion used for in programming?
sobes.tech AI
Answer from AI
Recursion in programming is a method of solving a problem where a function calls itself to solve subproblems until it reaches a base case that stops further calls.
Recursion is useful for tasks that naturally break down into similar sub-tasks, such as:
- Traversing trees and graphs
- Calculating factorials
- Depth-first search
- Solving problems involving partitioning or combinatorics
Example of calculating factorial using recursion in Python:
def factorial(n):
if n == 0:
return 1 # base case
else:
return n * factorial(n - 1) # recursive call
print(factorial(5)) # Outputs 120
It is important that a recursive function has a base case, otherwise it will cause infinite calls and lead to a stack overflow error.