R Program to print the Fibonacci Sequence


March 2, 2023, Learn eTutorial
3627

What is Fibonacci Series

A Fibonacci series is a 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.

fibonacci series

How Fibonacci Sequence is implemented in R Program

In this R program, After accepting the user input we are printing the numbers 0 and 1 manually, then In the while loop find n'th term by adding the (n-1) and (n-2) terms and update the numbers and increment the count by 1.

Learn more about how to print the Fibonacci series using a 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