Junior
What is the difference between implementing the same task using recursion and a loop?
sobes.tech AI
Answer from AI
Recursion uses a function call to itself to solve a problem, breaking it down into smaller subproblems until reaching the base case. A loop, on the other hand, repeats a block of code a certain number of times or until a condition is met.
| Characteristic | Recursion | Loop |
|---|---|---|
| Execution | Function call | Iteration |
| Memory | Uses call stack | Uses counter/condition variables |
| Readability | Can be more concise for some tasks | Often more straightforward |
| Performance | Can be slower due to call overhead | Usually more efficient |
| Stack Overflow | Risk of overflow with deep recursion | No risk of stack overflow |
Example in C# (factorial):
Recursive implementation:
// Recursive calculation of factorial
int FactorialRecursive(int n)
{
if (n == 0)
{
return 1; // Base case
}
return n * FactorialRecursive(n - 1); // Recursive call
}
Loop implementation:
// Calculation of factorial using a loop
int FactorialIterative(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}