Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Factorial Function
What is the output of the following C code when calling
factorial(4)?DSA C
int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } int main() { int result = factorial(4); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Remember factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The function calls itself reducing n by 1 until it reaches 0, then multiplies all values: 4 * 3 * 2 * 1 = 24.
❓ Predict Output
intermediate2:00remaining
Output of Recursive Sum Function
What is printed when the following C code runs
sum(3)?DSA C
int sum(int n) { if (n == 0) { return 0; } else { return n + sum(n - 1); } } int main() { int result = sum(3); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Sum of numbers from 1 to 3 is 6.
✗ Incorrect
The function adds n to the sum of numbers below it until it reaches 0: 3 + 2 + 1 + 0 = 6.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Fibonacci Function
What error will occur when running this C code?
DSA C
int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } int main() { int result = fibonacci(-1); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Check what happens when n is negative.
✗ Incorrect
The function does not handle negative inputs, so it keeps calling itself with decreasing n, never reaching base cases, causing infinite recursion and stack overflow.
🧠 Conceptual
advanced1:30remaining
Base Case Importance in Recursion
Why is the base case essential in a recursive function?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
The base case tells the function when to stop calling itself, preventing infinite loops and stack overflow.
❓ Predict Output
expert2:30remaining
Output of Recursive String Length Function
What is the output of this C code when calling
strlen_recursive("abc")?DSA C
#include <stdio.h> int strlen_recursive(const char *str) { if (*str == '\0') { return 0; } else { return 1 + strlen_recursive(str + 1); } } int main() { int length = strlen_recursive("abc"); printf("%d\n", length); return 0; }
Attempts:
2 left
💡 Hint
Count characters until the null character '\0'.
✗ Incorrect
The function counts each character until it finds the end '\0', so for "abc" it returns 3.