Challenge - 5 Problems
Factorial Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this factorial recursion code?
Consider the following C code that calculates factorial using recursion. What will be printed when n = 4?
DSA C
int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } int main() { int n = 4; int result = factorial(n); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
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
intermediate2:00remaining
What is the output when factorial is called with n = 0?
Look at this factorial function. What will it print when n = 0?
DSA C
int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } int main() { int n = 0; int result = factorial(n); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
Factorial of zero is defined as 1.
✗ Incorrect
By definition, factorial(0) = 1. The base case returns 1 when n is 0.
🔧 Debug
advanced2:00remaining
What error occurs when calling factorial(-1)?
Consider this factorial function. What happens if we call factorial(-1)?
DSA C
int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } int main() { int n = -1; int result = factorial(n); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
Check if the base case handles negative numbers.
✗ Incorrect
The base case only stops recursion when n == 0. For n = -1, it keeps calling factorial with decreasing n, causing infinite recursion and stack overflow.
❓ Predict Output
advanced2:00remaining
What is the output of this modified factorial function?
What will this code print when n = 3?
DSA C
int factorial(int n) { if (n <= 1) { return 1; } return n * factorial(n - 1); } int main() { int n = 3; int result = factorial(n); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
Factorial of 3 is 3 * 2 * 1.
✗ Incorrect
The base case now stops recursion when n <= 1, so factorial(3) = 3 * factorial(2) = 3 * 2 = 6.
🧠 Conceptual
expert2:00remaining
Why is recursion not always the best choice for factorial calculation?
Which of the following is the main reason recursion might be less efficient than iteration for factorial calculation?
Attempts:
2 left
💡 Hint
Think about what happens each time a function calls itself.
✗ Incorrect
Each recursive call adds a new frame to the call stack, using more memory. Iteration uses a single frame and is more memory efficient.