Counting Rabbits (Calculating the Fibonacci Series Using a Recursive Function)
<HTML>
<HEAD>
<SCRIPT>
function Fibonacci (inNum) {
if (inNum == 0)
var FibonacciNum = 0;
else {
if (inNum == 1)
FibonacciNum = 1;
else {
// recursive function call
FibonacciNum = Fibonacci(inNum - 2) + Fibonacci(inNum - 1);
}
}
return FibonacciNum;
}
function writeFibonaccis(topFibonacci) {
for (var i=0; i <= topFibonacci ; i++) {
document.write ("Fibonacci(" + i + ") = " + Fibonacci(i) + " <br>");
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM Name="theForm">
<TABLE cellspacing=5>
<TR>
<TD>
<INPUT Type=Text Name="numFibonaccis">
<TD>
<INPUT Type=Button Value="Show Fibonaccis" onClick='writeFibonaccis(numFibonaccis.value);'>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Related examples in the same category