Junior — Middle
What are the ways to replace the use of recursive calls in a program?
sobes.tech AI
Answer from AI
Recursive calls can be replaced with the following methods:
- Iterative approach — use loops (
for,while) instead of recursion. This often reduces memory usage and avoids stack overflow.
Example: calculating factorial iteratively instead of recursively.
# Recursive
# def factorial(n):
# if n == 0:
# return 1
# else:
# return n * factorial(n-1)
# Iterative
def factorial(n):
result = 1
for i in range(2, n+1):
result *= i
return result
-
Using a stack or custom data structure — simulate recursion with an explicit stack.
-
Tail recursion — if the language supports tail recursion optimization, rewrite the function so that the recursive call is the last operation.
-
Dynamic programming — store intermediate results to avoid repeated calls.
The choice of method depends on the problem and memory and time constraints.