0
0
R Programmingprogramming~20 mins

Recursive functions in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Recursive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A120
BError: object 'factorial' not found
C10
D24
Attempts:
2 left
💡 Hint
Remember factorial of 4 is 4 * 3 * 2 * 1.
Predict Output
intermediate
2: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)
A5
B8
C3
DError: recursive call limit reached
Attempts:
2 left
💡 Hint
Fibonacci sequence starts 0,1,1,2,3,5...
🔧 Debug
advanced
2: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)
A6
BError: argument is missing, with no default
CError: object 'sum_recursive' not found
DError: recursive call limit reached
Attempts:
2 left
💡 Hint
Check how the recursive call is made inside the function.
Predict Output
advanced
2: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')
A"cba"
B"abc"
CError: non-numeric argument to binary operator
D"bac"
Attempts:
2 left
💡 Hint
The function takes last character and appends reversed rest.
🧠 Conceptual
expert
2: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)
AThe base case is missing so recursion never stops.
BThe function has a syntax error causing infinite calls.
CThe function never reaches the base case because n increases instead of decreasing.
DThe function calls itself with the same argument causing infinite loop.
Attempts:
2 left
💡 Hint
Check how the argument changes in recursive calls.