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.
while(counter < n + 1)if(counter <= 1)nextTerm = celsenextTerm = firstTerm + secondTermfirstTerm = secondTermsecondTerm = nextTermendcounter += 1end
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.It prints the first nth
terms of a Fibonacci series.
# 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)
getFibonacci()
, which takes the nth
term specified and returns the first nth
term of a Fibonacci series.nth
number of terms of a Fibonacci series.