Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the function call itself recursively.
DSA C++
void countdown(int n) {
if (n == 0) {
return;
}
std::cout << n << " ";
countdown([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling countdown with n + 1 causes infinite recursion.
Calling countdown with n does not reduce the problem size.
✗ Incorrect
The function should call itself with n - 1 to count down towards zero.
2fill in blank
mediumComplete the code to calculate factorial of n recursively.
DSA C++
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Returning n instead of recursive call result.
✗ Incorrect
Factorial of n is n times factorial of n-1.
3fill in blank
hardFix the error in the recursive Fibonacci function call.
DSA C++
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci([1]) + fibonacci(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n instead of n-1 in first call.
✗ Incorrect
Fibonacci calls fibonacci(n-1) and fibonacci(n-2) to sum previous two numbers.
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from 1 to n.
DSA C++
int sumToN(int n) {
if (n == 0) {
return 0;
}
return n [1] sumToN([2]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition.
Not reducing n in recursive call.
✗ Incorrect
Sum from 1 to n is n plus sumToN(n-1).
5fill in blank
hardFill all three blanks to create a recursive function that reverses a string.
DSA C++
std::string reverseString(const std::string& s) {
if (s.empty()) {
return "";
}
return s.back() [1] reverseString(s.substr(0, [2]))[3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using s.size() + 1 causes out of range error.
Using subtraction operator instead of concatenation.
✗ Incorrect
The function appends last char plus reverse of substring excluding last char. The third blank is empty to complete the expression.
