Challenge - 5 Problems
Recursive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple factorial recursion
What is the output of this R code when calling
factorial(4)?R Programming
factorial <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
factorial(4)Attempts:
2 left
💡 Hint
Remember factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The function calls itself multiplying n by factorial of n-1 until n is 0, where it returns 1. So factorial(4) = 4*3*2*1 = 24.
❓ Predict Output
intermediate2:00remaining
Output of Fibonacci recursive function
What is the output of
fib(5) given this R function?R Programming
fib <- function(n) {
if (n <= 1) {
return(n)
} else {
return(fib(n - 1) + fib(n - 2))
}
}
fib(5)Attempts:
2 left
💡 Hint
Fibonacci sequence starts 0,1,1,2,3,5...
✗ Incorrect
fib(5) = fib(4) + fib(3) = 3 + 2 = 5. The function returns the 5th Fibonacci number starting from 0.
🔧 Debug
advanced2:00remaining
Identify the error in this recursive sum function
What error will this R code produce when calling
sum_recursive(3)?R Programming
sum_recursive <- function(n) {
if (n == 0) {
return(0)
} else {
return(n + sum_recursive)
}
}
sum_recursive(3)Attempts:
2 left
💡 Hint
Check how the recursive call is made inside the function.
✗ Incorrect
The recursive call is missing the argument n-1, so R tries to call sum_recursive() without arguments causing an error about missing argument.
❓ Predict Output
advanced2:00remaining
Output of recursive string reversal
What is the output of
reverse_str('abc') with this R function?R Programming
reverse_str <- function(s) {
if (nchar(s) == 0) {
return("")
} else {
return(paste0(substr(s, nchar(s), nchar(s)), reverse_str(substr(s, 1, nchar(s) - 1))))
}
}
reverse_str('abc')Attempts:
2 left
💡 Hint
The function takes last character and appends reversed rest.
✗ Incorrect
The function takes last character 'c' and appends reverse of 'ab' which is 'ba', so output is 'cba'.
🧠 Conceptual
expert2:00remaining
Maximum recursion depth error cause
Which option best explains why this recursive R function causes a 'maximum recursion depth exceeded' error?
R Programming
infinite_recursion <- function(n) {
if (n == 0) {
return(0)
} else {
return(infinite_recursion(n + 1))
}
}
infinite_recursion(1)Attempts:
2 left
💡 Hint
Check how the argument changes in recursive calls.
✗ Incorrect
The function increases n each call, so it never reaches n == 0 base case, causing infinite recursion until limit is reached.