Choose the best scenario where recursion is generally preferred over iteration.
Think about problems that break down into smaller similar problems.
Recursion is preferred when the problem naturally fits a hierarchical structure, such as trees or graphs, because it simplifies code and matches the problem's nature.
What is the output of the following C++ code?
int factorial_recursive(int n) {
if (n <= 1) return 1;
return n * factorial_recursive(n - 1);
}
int factorial_iterative(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int n = 4;
std::cout << factorial_recursive(n) << " " << factorial_iterative(n) << std::endl;
return 0;
}int factorial_recursive(int n) { if (n <= 1) return 1; return n * factorial_recursive(n - 1); } int factorial_iterative(int n) { int result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } int main() { int n = 4; std::cout << factorial_recursive(n) << " " << factorial_iterative(n) << std::endl; return 0; }
Calculate 4! (4 factorial) both ways.
4! = 4 * 3 * 2 * 1 = 24. Both recursive and iterative functions compute this correctly.
What happens when running this C++ code?
void recurse(int n) {
if (n == 0) return;
recurse(n - 1);
}
int main() {
recurse(1000000);
std::cout << "Done" << std::endl;
return 0;
}void recurse(int n) { if (n == 0) return; recurse(n - 1); } int main() { recurse(1000000); std::cout << "Done" << std::endl; return 0; }
Consider the maximum recursion depth allowed by the system stack.
Recursing one million times exceeds typical stack size, causing a stack overflow runtime error.
Choose the best reason to prefer iteration instead of recursion.
Think about memory and performance limits.
Iteration avoids the overhead and risk of stack overflow that deep recursion can cause, making it better for large or simple repeated tasks.
You want to compute the 30th Fibonacci number efficiently. Which approach is best?
Consider time complexity and memory usage.
Simple recursion is slow (exponential time). Memoization helps but uses extra memory. Iteration is fast and uses minimal memory, best for computing a single Fibonacci number efficiently.
