Related Tags

ruby

# How to print the Fibonacci series in Ruby using a while loop

okwudili onyejiaku

### Overview

A Fibonacci series is a series of numbers in which the next number is the sum of the previous two numbers. The first two numbers are 0 and 1. The third number is the sum of the previous two, and so on.

For example, the following is a Fibonacci series: 0, 1, 1, 2, 3, 5 .... If we see the number 5, it is the sum of the previous two numbers, which are 2 and 3.

In this shot, we'll print the first nth terms of the Fibonacci series in Ruby using while loop.

### Syntax

while(counter < n + 1)
if(counter <= 1)
nextTerm = c
else
nextTerm = firstTerm + secondTerm
firstTerm = secondTerm
secondTerm = nextTerm
end
counter += 1
end
Syntax to print the Fibonacci Series in Ruby

### Parameters

• counter: This serves as the counter for our loop.
• n: This represents the nth number of terms of the Fibonacci series we want to get.
• nextTerm: This represents the next term as the series progresses.
• firstTerm: This represents the first term of the series as the loop progresses.
• secondTerm: This represents the second term of the series as the loop progresses.

### Return value

It prints the first nth terms of a Fibonacci series.

### Example

# create a function to get Fibonacii series
def getFibonacci(n)
firstTerm = 0
secondTerm = 1
nextTerm = 0
counter = 1
result = []

puts "The first #{n} terms of Fibonacci series are:-"
result.push(firstTerm)
while(counter <= n + 1)
if(counter <= 1)
nextTerm = counter
else
result.push(nextTerm)
nextTerm = firstTerm + secondTerm
firstTerm = secondTerm
secondTerm = nextTerm
end
counter += 1
end
# print results
puts result.to_s
end

# create some terms
term1 = 10
term2 = 15
term3 = 50

# get some first nth terms of a Fibonacci series
getFibonacci(term1)
getFibonacci(term2)
getFibonacci(term3)
Example to print the first nth term of a Fibonacci Series in Ruby

### Explanation

• Line 2: We create a function called getFibonacci(), which takes the nth term specified and returns the first nth term of a Fibonacci series.
• Line 27–29: We create some terms. That is the nth number of terms of a Fibonacci series.
• Line 32–34: We invoke the function on the terms and print the results to the console.

RELATED TAGS

ruby

CONTRIBUTOR

okwudili onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time