w3resource

Fibonacci series with While loop in R

R Programming: Control Structure Exercise-4 with Solution

Write a R program to print the Fibonacci series using a while loop.

Sample Solution :

R Programming Code :

# Define a function to print the Fibonacci series up to a given limit using a while loop
print_fibonacci_series <- function(limit) {
    # Initialize variables to store the first two numbers of the Fibonacci series
    a <- 0
    b <- 1
    
    # Print the first two numbers of the Fibonacci series
    cat(a, b, sep = " ")
    
    # Iterate while the next Fibonacci number is less than or equal to the limit
    while (b <= limit) {
        # Calculate the next Fibonacci number
        next_num <- a + b
        
        # Print the next Fibonacci number
        cat(" ", next_num)
        
        # Update variables for the next iteration
        a <- b
        b <- next_num
    }
}

# Test the function with a limit of 100
limit <- 100
cat("Fibonacci series up to", limit, "is: ")
print_fibonacci_series(limit)

Output:

Fibonacci series up to 100 is: 0 1  1  2  3  5  8  13  21  34  55  89  144                  

Explatnaion:

In the exercise above,

  • Define the function:
    • The function "print_fibonacci_series()" takes one parameter 'limit', which specifies the upper limit for the Fibonacci series.
  • Initialization:
    • Inside the function, variables 'a' and 'b' are initialized to store the first two numbers of the Fibonacci series (0 and 1 respectively).
  • Print Initial Numbers:
    • The initial two numbers ('a' and 'b') of the Fibonacci series are printed using 'cat'.
  • While Loop:
    • The while loop iterates as long as the next Fibonacci number (next_num) is less than or equal to the specified limit.
  • Calculate the next Fibonacci number:
    • Inside the loop, the next Fibonacci number is calculated by adding a and b.
  • Print the next Fibonacci number:
    • The next Fibonacci number is printed using 'cat'.
  • Update variables:
    • The variables 'a' and 'b' are updated for the next iteration.
  • Testing the function:
    • The function is tested with a limit of 100.
    • The Fibonacci series up to the specified limit is printed to the console.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Sum of Even numbers using For loop in R.
Next: Check Prime number with While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-4.php