Junior — Middle
Explain the concept of recursive calls in programming
sobes.tech AI
Answer from AI
A recursive call is when a function calls itself to solve a problem. Recursion is typically used to break down a complex problem into simpler subproblems of the same type.
Example: calculating the factorial of a number n (n!) — the product of all numbers from 1 to n.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Here, the factorial function calls itself with a reduced argument until it reaches the base case (n == 0 or 1), after which it starts returning results back through the chain of calls.
It is important for a recursive function to have a base case, otherwise, the calls will be infinite and lead to a stack overflow.