Challenge - 5 Problems
Recursion Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Simple Recursive Function
What is the output of the following C++ code that uses recursion to print numbers?
DSA C++
void printNumbers(int n) { if (n == 0) return; printNumbers(n - 1); std::cout << n << " "; } int main() { printNumbers(3); return 0; }
Attempts:
2 left
💡 Hint
Think about when the print statement executes in relation to the recursive call.
✗ Incorrect
The function calls itself decreasing n until it reaches 0, then prints numbers on the way back up the call stack.
So it prints 1, then 2, then 3.
❓ Predict Output
intermediateSum of Numbers Using Recursion
What is the value of variable
result after running this C++ recursive function?DSA C++
int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); } int main() { int result = sum(4); std::cout << result; return 0; }
Attempts:
2 left
💡 Hint
Sum of first n natural numbers is n*(n+1)/2.
✗ Incorrect
The function adds numbers from 4 down to 1 recursively: 4 + 3 + 2 + 1 = 10.
🔧 Debug
advancedIdentify the Error in Recursive Function
What error will this C++ recursive function cause when called with
countdown(3)?DSA C++
void countdown(int n) { std::cout << n << " "; countdown(n - 1); } int main() { countdown(3); return 0; }
Attempts:
2 left
💡 Hint
Check if the function has a condition to stop calling itself.
✗ Incorrect
The function lacks a base case to stop recursion, so it calls itself infinitely until the program crashes with a stack overflow.
❓ Predict Output
advancedOutput of Recursive Factorial Function
What is the output of this C++ program that calculates factorial recursively?
DSA C++
int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } int main() { std::cout << factorial(5); return 0; }
Attempts:
2 left
💡 Hint
Factorial of 5 is 5*4*3*2*1.
✗ Incorrect
The function multiplies numbers from 5 down to 1 recursively, resulting in 120.
🧠 Conceptual
expertCall Stack Depth in Recursive Calls
If a recursive function calls itself with
n-1 until n == 0, what is the maximum depth of the call stack when called with n = 7?Attempts:
2 left
💡 Hint
Count how many times the function is called including the base case.
✗ Incorrect
The function calls itself 7 times decreasing n from 7 to 1, plus one more call when n == 0 (base case), so total depth is 8.
