Find the Fibonacci Sequence Using Recursive Function
Course- R Programming >
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source Code
# Program to diplay the Fibonacci
# sequence up to n-th term using
# recursive functions
recur_fibo <- function(n) {
if(n <= 1) {
return(n)
} else {
return(recur_fibo(n-1) + recur_fibo(n-2))
}
}
# take input from the user
nterms = as.integer(readline(prompt="How many terms? "))
# check if the number of terms is valid
if(nterms <= 0) {
print("Plese enter a positive integer")
} else {
print("Fibonacci sequence:")
for(i in 0:(nterms-1)) {
print(recur_fibo(i))
}
}
Output
How many terms? 9 [1] "Fibonacci sequence:" [1] 0 [1] 1 [1] 1 [1] 2 [1] 3 [1] 5 [1] 8 [1] 13 [1] 21
Here, we ask the user for the number of terms in the sequence. A recursive function recur_fibo()
is used to calculate the nth term of the sequence. We use a for
loop to iterate and calculate each term recursively.