Ruby - Print Fibonacci Series

1. Introduction

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The sequence goes 0, 1, 1, 2, 3, 5, 8, and so forth. In this tutorial, we'll create a Ruby program to generate the Fibonacci series up to a specified number of terms.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to input the number of terms for the Fibonacci series.

3. Implement a loop to generate the Fibonacci sequence.

4. Display the Fibonacci series to the user.

3. Code Program

# Prompt the user for the number of terms
puts "Enter the number of terms for the Fibonacci series:"
num_terms = gets.chomp.to_i
# Initial values for the Fibonacci series
a, b = 0, 1
# Check if the user wants at least one term
if num_terms <= 0
  puts "Please enter a positive integer."
else
  puts "The Fibonacci series upto #{num_terms} terms is:"
  num_terms.times do
    # Print the first number
    print "#{a}, "
    # Calculate the next number in the series
    temp = a
    a = b
    b = temp + b
  end
end

Output:

Enter the number of terms for the Fibonacci series:
7
The Fibonacci series upto 7 terms is:
0, 1, 1, 2, 3, 5, 8,

Explanation:

1. gets: This is used to capture user input.

2. chomp: Removes the newline character from the user input.

3. to_i: Converts the string input to an integer.

4. We initialize two variables, a and b, with the first two numbers of the Fibonacci series.

5. The times loop is then used to iterate over the required number of terms.

6. Within the loop, we print the current number, a, and then calculate the next number in the series by swapping values and summing them up.

The logic behind the Fibonacci series is that the next number is the sum of the two preceding numbers. This logic is implemented in the loop where we continuously add the last two numbers to get the next number in the series.


Comments