w3resource

Fibonacci nth term with Recursion in R

R Programming: Control Structure Exercise-7 with Solution

Write a R program function to calculate the nth term of the Fibonacci series using recursion.

Sample Solution :

R Programming Code :

# Define a function to calculate the nth term of the Fibonacci series using recursion
fibonacci <- function(n) {
    if (n <= 1) {  # Base case: If n is 0 or 1, return n
        return(n)
    } else {
        # Recursive case: Calculate the nth term using recursion
        return(fibonacci(n - 1) + fibonacci(n - 2))
    }
}

# Test the function with an example input
n <- 10  # Example input for which Fibonacci term is to be calculated
result <- fibonacci(n)

# Print the result
cat("The", n, "th term of the Fibonacci series is:", result, "\n")

Output:

The 10 th term of the Fibonacci series is: 55               

Explatnaion:

In the exercise above,

  • The "fibonacci()" function takes one parameter 'n', which represents the position of the term in the Fibonacci series to be calculated.
  • It starts with a base case: if 'n' is 0 or 1, it returns 'n' because the Fibonacci sequence starts with 0 and 1.
  • If 'n' is greater than 1, it uses recursion to calculate the nth term by adding the (n-1)th term and the (n-2)th term of the Fibonacci series.
  • The function is then tested with an example input ('n'), and the result is printed to the console.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Multiplication Table with For loop in R.
Next: Factorial calculation with Recursion in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.