In the Fibonacci sequence is a series, next number is the addition of the last two numbers, the Fibonacci series starts with 0, and 1.
In this program, the user will take a length of the series through prompt and find Fibonacci Sequence by using for loop.
<!DOCTYPE html>
<html>
<body>
<script>
function fibonacci()
{
var a=0,b=1,fib=0,n,i;
var n=prompt("Enter the length of series:");
document.write(a+"</br> "+b+"</br>");
for(i=2;i<n;i++)
{
fib=a+b;
document.write(fib+"</br>");
a=b;
b=fib;
}
}
</script>
<form>
<input type="button" value="fibonacci" onclick="fibonacci();">
</form>
</body>
</html>
Input has taken through javascript prompt method
Enter the length of series:9 0 1 1 2 3 5 8 13 21
n
.a
and b
.fib=a+b
.fib
and for finding the next Fibonacci series number, copy the value of b
into a
, i.e a=b
, and copy the fib
value to b
, i.e, b=fib
inside for loop.In this program, the user will take a length of the series through prompt and find Fibonacci Sequence by using while loop.
<!DOCTYPE html>
<html>
<body>
<script>
function fibonacci()
{
var a=0,b=1,fib=0,n,i;
var n=prompt("Enter the length of series:");
document.write(a+"</br> "+b+"</br>");
i=2;
while(i<n)
{
fib=a+b;
document.write(fib+"</br>");
a=b;
b=fib;
i++;
}
}
</script>
<form>
<input type="button" value="fibonacci" title="fibonacci series" onclick="fibonacci();">
</form>
</body>
</html>
Input has taken through javascript prompt method
Enter the length of series:10 0 1 1 2 3 5 8 13 21 34