Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the base case value for factorial.
DSA C++
int factorial(int n) {
if (n == 0) {
return [1];
}
return n * factorial(n - 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 for the base case causes all results to be zero.
Returning n instead of 1 in the base case.
✗ Incorrect
The factorial of 0 is defined as 1, so the base case returns 1.
2fill in blank
mediumComplete the code to correctly call the recursive factorial function.
DSA C++
int factorial(int n) {
if (n == 0) {
return 1;
}
return n [1] factorial(n - 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using division or subtraction which are incorrect.
✗ Incorrect
Factorial multiplies n by factorial of (n-1), so the operator is '*'.
3fill in blank
hardFix the error in the base case condition to correctly check for zero.
DSA C++
int factorial(int n) {
if (n [1] 0) {
return 1;
}
return n * factorial(n - 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' causes infinite recursion.
Using '>' or '<' changes the logic incorrectly.
✗ Incorrect
The base case triggers when n equals 0, so the condition must be '== 0'.
4fill in blank
hardFill both blanks to complete the recursive factorial function with correct base case and recursive call.
DSA C++
int factorial(int n) {
if (n [1] 0) {
return [2];
}
return n * factorial(n - 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' in the condition.
Returning 0 instead of 1 in the base case.
✗ Incorrect
The base case checks if n == 0 and returns 1 to stop recursion.
5fill in blank
hardFill all three blanks to create a factorial function that handles negative input by returning -1, and computes factorial recursively for non-negative input.
DSA C++
int factorial(int n) {
if (n [1] 0) {
return [2];
} else if (n < 0) {
return [3];
}
return n * factorial(n - 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Not handling negative input causes infinite recursion.
Returning 0 for base case instead of 1.
✗ Incorrect
Check if n == 0 to return 1; if n < 0 return -1 to indicate invalid input.
