Introduction
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. This guide will walk you through writing an R program that generates the Fibonacci sequence up to a specified number of terms.
Problem Statement
Create an R program that:
- Prompts the user to enter the number of terms for the Fibonacci sequence.
- Generates the Fibonacci sequence up to the specified number of terms.
- Displays the generated sequence.
Example:
- Input:
7 - Output:
0, 1, 1, 2, 3, 5, 8
Solution Steps
- Read the Number of Terms: Use the
readline()function to take the number of terms as input from the user. - Convert the Input to Numeric: Convert the input from a character string to a numeric value using the
as.numeric()function. - Initialize the Sequence: Start the sequence with the first two terms, 0 and 1.
- Generate the Sequence: Use a loop to generate the remaining terms of the sequence.
- Display the Sequence: Use the
print()function to display the generated Fibonacci sequence.
R Program
# R Program to Generate Fibonacci Sequence
# Author: https://www.javaguides.net/
# Step 1: Read the number of terms from the user
n_terms <- as.numeric(readline(prompt = "Enter the number of terms: "))
# Step 2: Initialize the first two terms of the Fibonacci sequence
fib_sequence <- numeric(n_terms)
fib_sequence[1] <- 0
if (n_terms > 1) {
fib_sequence[2] <- 1
# Step 3: Generate the Fibonacci sequence
for (i in 3:n_terms) {
fib_sequence[i] <- fib_sequence[i - 1] + fib_sequence[i - 2]
}
}
# Step 4: Display the Fibonacci sequence
print(paste("Fibonacci sequence up to", n_terms, "terms:"))
print(fib_sequence)
Explanation
Step 1: Read the Number of Terms
- The
readline()function prompts the user to enter the number of terms. The input is read as a string, so it is converted to a numeric value usingas.numeric().
Step 2: Initialize the First Two Terms
- The Fibonacci sequence starts with 0 and 1, so these values are assigned to the first two elements of the
fib_sequencevector.
Step 3: Generate the Fibonacci Sequence
- If the number of terms is greater than 2, a loop is used to generate the remaining terms of the sequence. Each new term is the sum of the two preceding ones.
Step 4: Display the Fibonacci Sequence
- The
print()function is used to display the entire Fibonacci sequence up to the specified number of terms.
Output Example
Example:
Enter the number of terms: 7
[1] "Fibonacci sequence up to 7 terms:"
[1] 0 1 1 2 3 5 8
Conclusion
This R program demonstrates how to generate a Fibonacci sequence for a given number of terms. It covers basic programming concepts such as loops, user input, and sequence generation, making it a useful example for beginners learning R programming.