Challenge - 5 Problems
Factorial Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Factorial Call
What is the output of the following Java code that calculates factorial recursively?
DSA Java
public class Factorial { public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { System.out.println(factorial(4)); } }
Attempts:
2 left
💡 Hint
Remember 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 for Factorial of Zero
What will be printed when the factorial function is called with 0?
DSA Java
public class Factorial { public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { System.out.println(factorial(0)); } }
Attempts:
2 left
💡 Hint
Factorial of zero is defined as 1.
✗ Incorrect
By definition, factorial of 0 is 1. The base case in the code returns 1 when n is 0.
🔧 Debug
advancedIdentify the Error in Recursive Factorial
What error will this code produce when run?
DSA Java
public class Factorial { public static int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { System.out.println(factorial(0)); } }
Attempts:
2 left
💡 Hint
Check what happens when n is 0 in the recursive call.
✗ Incorrect
The base case is for n == 1, so factorial(0) calls factorial(-1), then factorial(-2), and so on, causing infinite recursion and StackOverflowError.
🧠 Conceptual
advancedRecursion Depth for Factorial of 5
How many times is the factorial function called when calculating factorial(5)?
Attempts:
2 left
💡 Hint
Count the initial call plus each recursive call down to the base case.
✗ Incorrect
The calls are factorial(5), factorial(4), factorial(3), factorial(2), factorial(1), factorial(0) if base case is n==0, so total 6 calls.
🚀 Application
expertOutput of Modified Factorial with Print Statements
What is the output of this Java program that prints each call and returns factorial?
DSA Java
public class Factorial { public static int factorial(int n) { System.out.println("Call factorial(" + n + ")"); if (n == 0) { return 1; } else { int result = n * factorial(n - 1); System.out.println("Return " + result + " for factorial(" + n + ")"); return result; } } public static void main(String[] args) { factorial(2); } }
Attempts:
2 left
💡 Hint
Trace the calls and returns carefully, noting the order of print statements.
✗ Incorrect
The calls print first, then base case returns 1. Returns print after recursive calls. factorial(1) returns 1*1=1, factorial(2) returns 2*1=2. The return print for factorial(1) shows 1, not 2.
