32. JavaScript Program to find the Fibonacci series of a given number.
How does this program work?
- This program is used to find the Fibonacci series of a given number using JavaScript.
- Fibonacci series means the previous two elements are added to get the next element starting with 0 and 1.
- First we initializing first and second number as 0 and 1, and print them.
- The third number will be the sum of the first two numbers by using loop.
Here is the code
<html>
<head>
<title>JavaScript program to find the Fibonacci series of a given number</title>
</head>
<body>
<table>
<tr>
<td> <input type="text" name="a" id="first" placeholder="Enter a number"> </td>
</tr>
<tr>
<td> <button onclick="fibonacci ()" >Submit</button> </td>
</tr>
</table>
<div id="num"></div>
</body>
<script type="text/javascript">
function fibonacci()
{
var n,i,c;
n = parseInt(document.getElementById ("first").value);
var a = 0;
var b = 1;
document.write("Fibonacci series of "+n+" is :</br>");
document.write(a + " "+ b);
for(i = 2; i < n; i++ )
{
c = a +b;
a = b;
b = c;
document.write(" "+ c+" ");
}
}
</script>
</html>