0
0
R Programmingprogramming~10 mins

Recursive functions in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a recursive function that calculates the factorial of a number.

R Programming
factorial <- function(n) {
  if (n == 0) {
    return(1)
  } else {
    return(n * factorial([1]))
  }
}
Drag options to blanks, or click blank then click option'
An * 1
Bn + 1
Cn - 1
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using 1 does not reduce the problem size.
2fill in blank
medium

Complete the code to define a recursive function that computes the nth Fibonacci number.

R Programming
fibonacci <- function(n) {
  if (n <= 1) {
    return(n)
  } else {
    return(fibonacci([1]) + fibonacci(n - 2))
  }
}
Drag options to blanks, or click blank then click option'
A1
Bn + 1
Cn - 2
Dn - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n - 2 for both calls is incorrect.
3fill in blank
hard

Fix the error in the recursive function that sums numbers from 1 to n.

R Programming
sum_to_n <- function(n) {
  if (n == 1) {
    return(1)
  } else {
    return(n + sum_to_n([1]))
  }
}
Drag options to blanks, or click blank then click option'
An + 1
Bn - 1
C1
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using 1 does not reduce the problem size.
4fill in blank
hard

Fill both blanks to create a recursive function that counts down from n to 1 and prints each number.

R Programming
countdown <- function(n) {
  if (n == 0) {
    return()
  }
  print([1])
  countdown([2])
}
Drag options to blanks, or click blank then click option'
An
Bn - 1
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Printing n - 1 before the call changes the order.
Calling countdown with n + 1 causes infinite recursion.
5fill in blank
hard

Fill all three blanks to define a recursive function that reverses a string.

R Programming
reverse_string <- function(s) {
  if (nchar(s) == 0) {
    return("")
  } else {
    return(paste0(substring(s, [1]), reverse_string(substring(s, [2], [3]))) )
  }
}
Drag options to blanks, or click blank then click option'
Anchar(s)
B1
C2
Dnchar(s) - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using fixed numbers instead of nchar(s) causes errors.
Incorrect substring indices cause wrong output.