Challenge - 5 Problems
Factorial Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Factorial Function Call
What is the output of the following C++ code that calculates factorial using recursion?
DSA C++
#include <iostream> int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { int result = factorial(4); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Recall factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The factorial function multiplies n by factorial of n-1 until n is 0, where it returns 1. So factorial(4) = 4*3*2*1 = 24.
❓ Predict Output
intermediateOutput When Calling Factorial with Zero
What will be printed when the factorial function is called with 0?
DSA C++
#include <iostream> int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { std::cout << factorial(0) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Factorial of zero is defined as 1.
✗ Incorrect
By definition, factorial(0) returns 1 as the base case in the recursion.
🔧 Debug
advancedIdentify the Error in Recursive Factorial Code
What error will this code produce when compiled and run?
DSA C++
#include <iostream> int factorial(int n) { if (n == 0) return 1; else return n * factorial(n + 1); } int main() { std::cout << factorial(3) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check the recursive call argument and base case.
✗ Incorrect
The recursive call increases n instead of decreasing, so the base case is never reached, causing infinite recursion and stack overflow.
🧠 Conceptual
advancedWhy is Base Case Important in Recursive Factorial?
What is the main purpose of the base case in a recursive factorial function?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
The base case stops the recursion by providing a condition where the function returns without calling itself again.
❓ Predict Output
expertOutput of Factorial with Negative Input
What will happen when the factorial function below is called with -1?
DSA C++
#include <iostream> int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { std::cout << factorial(-1) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Consider what happens when n is negative and base case is only for zero.
✗ Incorrect
Since the base case only stops recursion at n == 0, negative inputs cause the function to call factorial with decreasing n indefinitely, causing stack overflow.
