w3resource

R Programming: Generate first 10 Fibonacci numbers

R Programming: Basic Exercise-5 with Solution

Write a R program to get the first 10 Fibonacci numbers.

Sample Solution :

R Programming Code :

# Initialize a numeric vector 'Fibonacci' of length 10 with zeros
Fibonacci <- numeric(10)

# Set the first two elements of the 'Fibonacci' vector to 1
Fibonacci[1] <- Fibonacci[2] <- 1

# Loop through indices 3 to 10 to calculate Fibonacci numbers
# Each element is the sum of the two preceding elements
for (i in 3:10) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]

# Print a message indicating that the first 10 Fibonacci numbers will be shown
print("First 10 Fibonacci numbers:")

# Print the 'Fibonacci' vector to display the first 10 Fibonacci numbers
print(Fibonacci)

Output:

[1] "First 10 Fibonacci numbers:"
 [1]  1  1  2  3  5  8 13 21 34 55                         

Explanation:

  • Initialize Fibonacci Vector:
    • Fibonacci <- numeric(10): Creates a numeric vector Fibonacci of length 10, initialized with zeros.
  • Set Initial Values:
    • Fibonacci[1] <- Fibonacci[2] <- 1: Sets the first two elements of the vector to 1. These represent the first two numbers in the Fibonacci sequence.
  • Compute Fibonacci Sequence:
    • for (i in 3:10) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]: Loops from the third to the tenth element. Each element is computed as the sum of the two preceding elements.
  • Print Results:
    • print("First 10 Fibonacci numbers:"): Prints a message indicating that the following output is the Fibonacci sequence.
    • print(Fibonacci): Displays the vector containing the first 10 Fibonacci numbers.

R Programming Code Editor:



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

Previous: Write a R program to create a vector which contains 10 random integer values between -50 and +50.
Next: Write a R program to get all prime numbers up to a given number (based on the sieve of Eratosthenes).

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://www.w3resource.com/r-programming-exercises/basic/r-programming-basic-exercise-5.php