Fibonacci series in js
In the Fibonacci series, the new number is the sum of the preceding two numbers. This process is repeated to form a Fibonacci series. And we will write program in js to get Fibonacci series.
How to write a program in js to get Fibonacci series
We must have two numbers to start a Fibonacci series. We have two numbers in the following example i.e. 0 and 1.
0,1We get the new number by adding the preceding two numbers i.e. 0+1=1. Thus the given series is:
0,1,1The next number is obtained by adding the preceding two numbers i.e. 1+1=2. Thus the given series is:
0,1,1,2So this is the basic principle of how to form a Fibonacci series. We have got four terms in our Fibonacci series. Now what if we want to get 100th term. Obviously, we are lazy and can not follow this way.
Here we need to write some program to get our work done within no time. OK. A program must write a pseudo code before writing a program in some specific language.
So here we go. Since we know how to form a Fibonacci series. We write those steps in simple English language.
function Fibonacci (n)
{
Define A, B, C, i, fib,
set A to 0
set B to 1
set i to 3
if(n==1)
{
SET set fib to
}
else if(n==2)
{
SET set fib to
}
else
{
While i is less than or equal to n
{
Add A and B to get C
PUT B in A
PUT C in B
PUSH C in fib
Increment i
}
}
return fib;
}
Now we will write a JavaScript function to get Fibonacci series.
function fibonacci (nth){
let a, b, c, fib;
a=0;
b=1;
if(nth==1)
{
fib=[a];
}
else if(nth==2)
{
fib=[a,b];
}
else
{
fib=[a,b];
for(let i=3;i<=nth;i++)
{
c = a+b;
a = b;
b = c;
fib.push(c);
}
}
return fib;
}
JS fibonacci() function returns an array of Fibonacci numbers that you can print anywhere.
In this function the new number is new number by adding the preceding numbers.
Summary
There are multiple ways to write a JavaScript function to get a Fibonacci series. It depends upon the approach you use to write your program. You only need to understand how to solve a problem.
Tags