Junior — Middle
Explain the concept of recursive functions and how they work
sobes.tech AI
Answer from AI
A recursive function is a function that calls itself to solve a problem. It breaks down the problem into simpler subproblems of the same type until it reaches a base case where further calls are not needed.
How it works:
- The function calls itself with modified parameters, bringing the solution closer to the base case.
- When the base case is reached, the function starts returning results back through the chain of calls.
Example: calculating the factorial of a number n (n!)
def factorial(n):
if n == 0:
return 1 # base case
else:
return n * factorial(n - 1) # recursive call
Here, factorial calls itself with n-1 until it reaches 0, after which it starts returning values up the chain.
Recursion is useful for problems that naturally break down into similar subproblems, such as tree traversal, Fibonacci number calculation, sorting, etc.