Today lets see how to generate Fibonacci Series using JavaScript programming.
First Thing First: What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.
Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34
How Its Formed:
0 <– First Number
1 <– Second Number
1 <– = 1 + 0
2 <– = 1 + 1
3 <– = 2 + 1
5 <– = 3 + 2
8 <– = 5 + 3
13 <– = 8 + 5
21 <– = 13 + 8
34 <– = 21 + 13
Video Explaining The JavaScript Code To Generate Fibonacci Series:
[youtube https://www.youtube.com/watch?v=V8WwUwOxm5M]
Some points to keep in mind:
1. In Javascript, it is not mandatory to declare a variable before using it. But still its a good practice to declare it before using.
2. Using html comments inside javascript code ensures that, the old browsers which do not support javascript will ignore all the code written inside the script tags.
3. If we give a very large number while entering the limit, then the loop start executing and the browser memory will soon exhaust and the browser may stop responding.
4. You can use any valid html coding inside document.write statement, as the output will be then processed by a html browser.
JavaScript Code Shown In Above Video:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <title>Fibonacci Series</title> <script type="text/javascript"> <!-- var var1 = 0; var var2 = 1; var var3; var num = prompt("Enter the limit to generate fibonacci no",0); document.write(var1+"<br />"); document.write(var2+"<br />"); for(var i=3; i < = num;i++) { var3 = var1 + var2; var1 = var2; var2 = var3; document.write(var3+"<br />"); } // --> </script> |
In JavaScript:
Variable declaration is done using var keyword, followed by the variable name.
document.write is the output statement.
prompt is used to get the input from the user.
Even though the above program is easy, you may forget the logic when it is needed. So don’t forget to actually pullout a text editor and try it out yourself.
Sooperb explanation… :)
@asma, thanks a lot for your feedback..it means a lot for me
very goooddddd xplanation luv it
Muy buena explicacion y tmb facil de entennder
@daksh, @Danny, Thanks a lot for your comments.
“Muy buena explicacion y facil de entender”
in Spanish, means: Very good explanation and easy to understand :-)
superb explanation.thanks a lot
Here is little modified function of the Fibonachi number, with call of the function to the eight element
@svilen, Thanks for sharing it with us. I’m sure, it’ll be helpful to many.
Get get it wrong…This is not straight forward…But it works…I will stick to Satish’s codes. Thanks
Thanks a lot. It helped me a lot.
Great explanation Satish, video as well as code snippet really an advantage for beginners.