Open In App

R Program to Print the Fibonacci Sequence

Last Updated : 21 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Fibonacci sequence is a series of numbers in which each number (known as a Fibonacci number) is the sum of the two preceding ones. The sequence starts with 0 and 1, and then each subsequent number is the sum of the two previous numbers. The Fibonacci sequence has many applications in various fields, including mathematics, computer science, and nature.

To generate the Fibonacci sequence in R Programming Language, we will use a loop. The sequence is defined as follows:

  • The first two numbers are 0 and 1.
  • The next number is the sum of the two preceding numbers.

Steps:

To print the Fibonacci sequence in R, follow these steps:

  1. Take the input for the number of terms (n) to be generated in the sequence.
  2. Use a loop to generate the Fibonacci numbers.
  3. Print the numbers in the sequence.

R program to print the Fibonacci sequence using a loop

R




# Function to print the Fibonacci sequence using a loop
print_fibonacci <- function(n) {
  a <- 0
  b <- 1
 
  cat("Fibonacci Sequence:")
  for (i in 1:n) {
    cat(a, " ")
    next_num <- a + b
    a <- b
    b <- next_num
  }
}
 
# Example usage
number_of_terms <- 10
print_fibonacci(number_of_terms)


Output:

Fibonacci Sequence:0  1  1  2  3  5  8  13  21  34 

R program to print the Fibonacci sequence using Recursion

R




fibonacci <- function(n) {
  if (n <= 0) {
    return(NULL)
  } else if (n == 1) {
    return(0)
  } else if (n == 2) {
    return(1)
  } else {
    return(fibonacci(n - 1) + fibonacci(n - 2))
  }
}
 
print_fibonacci_sequence <- function(n) {
  if (n <= 0) {
    cat("Invalid input. Please enter a positive integer.\n")
    return()
  }
   
  cat("Fibonacci Sequence:")
  for (i in 1:n) {
    cat(" ", fibonacci(i))
  }
  cat("\n")
}
 
# Change the value of 'n' to the desired number of terms in the sequence
n <- 10
print_fibonacci_sequence(n)


Output:

Fibonacci Sequence:  0  1  1  2  3  5  8  13  21  34

  • Prints the Fibonacci sequence up to a specified number of terms.
  • Input: Positive integer n indicating the number of terms to print.
  • Checks if the input is valid (positive integer).
  • Prints an error message if the input is not valid.
  • Prints the terms of the sequence using the fibonacci function.
  • Set the variable n to determine how many terms of the Fibonacci sequence to display (e.g., n <- 10 for the first 10 terms).
  • Running the code with the chosen n will print the Fibonacci sequence up to the nth term.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads