R Program to print the Fibonacci Sequence

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.


STEP 1: prompting appropriate messages to the user

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

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

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

STEP 5:  if(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 nth by adding the last two terms and print 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 terms



R Source Code

                                          terms = as.integer(readline(prompt="How many terms? "))
# first two terms
num1 = 0
num2 = 1
count = 2
# check if the number of terms is valid
if(terms <= 0) {
print("Plese enter a positive integer")
} else {
if(terms == 1) {
print("Fibonacci sequence:")
} else {
print("Fibonacci sequence:")
while(count < terms) {
nth = num1 + num2
# update values
num1 = num2
num2 = nth
count = count + 1


How many terms? 7
[1] "Fibonacci sequence:"
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8