1. Introduction
The Fibonacci sequence is an intriguing series of numbers in which each number is the sum of the two preceding ones. Usually, the sequence starts with 0 and 1. Apart from its mathematical intrigue, the Fibonacci sequence is found in numerous natural phenomena and has applications in computer algorithms and financial markets. In this tutorial, we will explore how to craft an R program that generates the Fibonacci sequence for a given length.
2. Program Overview
The program's mission is to prompt the user for the number of terms they want from the Fibonacci sequence.
Post input, the program will display the sequence of that specified length.
3. Code Program
# Function to generate Fibonacci sequence up to n terms
fibonacci <- function(n) {
# Base cases
if (n <= 1) {
return(n)
} else {
return(fibonacci(n-1) + fibonacci(n-2))
}
}
# Ask the user for the number of terms they want
cat("Enter the number of terms for the Fibonacci sequence: ")
num_terms <- as.integer(readLines(n=1))
# Ensure the number of terms is non-negative
if (num_terms <= 0) {
cat("Error: Please enter a positive integer.\n")
} else {
cat("Fibonacci Sequence of", num_terms, "terms:\n")
for (i in 0:(num_terms-1)) {
cat(fibonacci(i), " ")
}
}
Output:
Enter the number of terms for the Fibonacci sequence: 7 Fibonacci Sequence of 7 terms: 0 1 1 2 3 5 8
4. Step By Step Explanation
1. We initiate our program by defining the fibonacci function. This function, employing recursion, calculates the Fibonacci sequence.
fibonacci <- function(n) {
# Base cases
if (n <= 1) {
return(n)
} else {
return(fibonacci(n-1) + fibonacci(n-2))
}
}
2. Inside the function, we set our base cases: the Fibonacci value for 0 is 0, and for 1, it's 1.
if (n <= 1) {
return(n)
}
3. For any other number n, the Fibonacci value is the sum of the Fibonacci values of n-1 and n-2.
return(fibonacci(n-1) + fibonacci(n-2))
4. The main program segment requests the user's desired number of Fibonacci sequence terms via the cat function.
cat("Enter the number of terms for the Fibonacci sequence: ")
5. Using readLines(n=1), the input is captured and, considering its character form, as.integer facilitates its conversion to an integer. This value is stored in the num_terms variable.
num_terms <- as.integer(readLines(n=1))
6. A quick validation check ensures the entered number is positive.
if (num_terms <= 0) {
cat("Error: Please enter a positive integer.\n")
}
7. If the number is valid, the program employs a loop to calculate and print each term in the Fibonacci sequence up to the specified number of terms.
8. The loop, running from 0 to num_terms-1, leverages the fibonacci function for each term, printing the sequence in a line.
for (i in 0:(num_terms-1)) {
cat(fibonacci(i), " ")
}
Comments
Post a Comment
Leave Comment