Junior — Middle
How to distinguish between recursive calls and iterative loops in programming?
sobes.tech AI
Answer from AI
Recursive calls are when a function calls itself to solve a subproblem, usually with a modified argument, and has a base case to stop. Iterative loops use constructs like for or while to repeat a block of code.
Differences:
- Recursion is suitable for problems that naturally break down into subproblems (e.g., tree traversal).
- Iteration is usually more memory-efficient as it does not require additional stack calls.
Example of factorial:
Recursion:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Iteration:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result