R Program to print the Fibonacci Sequence Using Recursive Function

What is Fibonacci Sequance ?

A Fibonacci series is a sequence or series of numbers that start from 0, 1, 1, 2, 3, and so on. In the Fibonacci sequence, we add the first two numbers manually as 0 and 1. All the rest of the Fibonacci sequence is obtained by calculating the sum of the previous two numbers for example the third number of the Fibonacci sequence will be 0+1=1 and so on. 

So in general we can define the nth term of a Fibonacci sequence will be calculated using the formula of finding the sum of (n-1)th and (n-2)th number.

How to implement Fibonacci Sequence Using Recursive Function in R Program?

We are using readline() function for taking the user's input. Given below are the steps which are used in the R program to print Fibonacci Sequence using Recursive Function. In this R program, we accept the user's input into the variable terms by providing an appropriate message to the user using 'prompt'. 

A function fibonacci() is used to calculate the nth term of the Fibonacci series. for loop used to iterate and calculate each term recursively.

Learn more about how to find the Fibonacci series without recursive function.

ALGORITHM

STEP 1: prompting appropriate messages to the user

STEP 2: take user input using readline() into variables total_terms

STEP 4: check the total_terms >0 for check variable total_terms is valid or not, if not re-enter the value

STEP5: If total_terms >0, using for loop call the function fibonacci() total_terms times for calculating nth term. and print the value which is returned from the function fibonacci()

Function fibonacci(n)

STEP 1: if n <= 1 then return n ,else goto step 2

STEP 2 : return fibonacci(n-1) + fibonacci(n-2) ,Call the function recursively

 

R Source Code

                                          # Function fibonacci

fibonacci <- function(n) {
    if(n <= 1) {
        return(n)
    } else {
        return(fibonacci(n-1) + fibonacci(n-2))
    }
}

# take input from the user
total_terms = as.integer(readline(prompt="How many terms? "))

# check if the total_terms is valid or not
if(total_terms<= 0) {
    print("Plese enter a positive integer")
} else {
    print("Fibonacci sequence:")
    for(i in 0:(total_terms-1)) {
        print(fibonacci(i))
    }
}
                                      

OUTPUT

How many terms? 10
[1] "Fibonacci sequence:"
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
[1] 21
[1] 34