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.
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.
# terms = as.integer(readline(prompt = "How many terms? "))
terms = as.integer(12)
# 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:")
print(n1)
} else {
print("Fibonacci sequence:")
print(num1)
print(num2)
while(count < terms) {
nth = num1 + num2
print(nth)
# update values
num1 = num2
num2 = nth
count = count + 1
}
}
}
## [1] "Fibonacci sequence:"
## [1] 0
## [1] 1
## [1] 1
## [1] 2
## [1] 3
## [1] 5
## [1] 8
## [1] 13
## [1] 21
## [1] 34
## [1] 55
## [1] 89
# terms = as.integer(readline(prompt = "How many terms? "))
terms = as.integer(23)
# 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:")
print(n1)
} else {
print("Fibonacci sequence:")
print(num1)
print(num2)
while(count < terms) {
nth = num1 + num2
print(nth)
# update values
num1 = num2
num2 = nth
count = count + 1
}
}
}
## [1] "Fibonacci sequence:"
## [1] 0
## [1] 1
## [1] 1
## [1] 2
## [1] 3
## [1] 5
## [1] 8
## [1] 13
## [1] 21
## [1] 34
## [1] 55
## [1] 89
## [1] 144
## [1] 233
## [1] 377
## [1] 610
## [1] 987
## [1] 1597
## [1] 2584
## [1] 4181
## [1] 6765
## [1] 10946
## [1] 17711