How to print the Fibonacci series in Ruby using a while loop
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 = celsenextTerm = firstTerm + secondTermfirstTerm = secondTermsecondTerm = nextTermendcounter += 1end
Syntax to print the Fibonacci Series in Ruby
Parameters
counter: This serves as the counter for our loop.
n: This represents thenthnumber 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 seriesdef getFibonacci(n)firstTerm = 0secondTerm = 1nextTerm = 0counter = 1result = []puts "The first #{n} terms of Fibonacci series are:-"result.push(firstTerm)while(counter <= n + 1)if(counter <= 1)nextTerm = counterelseresult.push(nextTerm)nextTerm = firstTerm + secondTermfirstTerm = secondTermsecondTerm = nextTermendcounter += 1end# print resultsputs result.to_send# create some termsterm1 = 10term2 = 15term3 = 50# get some first nth terms of a Fibonacci seriesgetFibonacci(term1)getFibonacci(term2)getFibonacci(term3)
Explanation
- Line 2: We create a function called
getFibonacci(), which takes thenthterm specified and returns the firstnthterm of a Fibonacci series.
- Line 27–29: We create some terms. That is the
nthnumber of terms of a Fibonacci series. - Line 32–34: We invoke the function on the terms and print the results to the console.