R Program to print the Fibonacci Sequence

What is Fibonacci Series

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.

Prime number Checking

How to print the Fibonacci Sequence

Here we are explaining how to write an R program to find the Fibonacci Sequence. We can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user.

How Fibonacci Sequence is implemented 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. In this R program, we accept the user's input into the variable terms by providing an appropriate message to the user using 'prompt'. In while loop finds the n'th term by adding the last two numbers.

Learn more about how to print the Fibonacci series using recursive function.

ALGORITHM

STEP 1: prompting appropriate messages to the user

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

STEP 3: first set num1=0 , num2=1

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

STEP 5:  if(total_terms >2), we use a while loop to find the next term

STEP 6:  in the while loop, we first print the two terms num1 and num2

STEP 7: calculate the next term nxt by adding the last two terms and printing it

STEP 8:update the values of num1 and num2 to the last two terms

STEP 9:continue until the number of terms reaches the total_terms 

R Source Code

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

num1 = 0 # first number
num2 = 1 # second number
count = 2
# check if the total_terms  is valid
if (total_terms  <= 0) {
    print("Please enter a positive integer")
} else {
    if (total_terms == 1) {
        print("Fibonacci sequence:")
        print(num1)
    } else {
        print("Fibonacci sequence:")
        print(num1)
        print(num2)
        while (count < total_terms  ) {
            nxt = num1 + num2
            print(nxt)
            # update values
            num1 = num2
            num2 = nxt
            count = count + 1
        }
    }
}
                                      

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