How to calculate factorial in JavaScript?

In this program we present 3 different programs that calculate using JavaScript. In each case the input n is to be stored in a textbox whose id is n, and answer will be displayed in a text field of id result. the text filed is being accessed using the document.GetElementById method. The value is accessed using the value attribute.

For loop


function f1()
{
var x=document.getElementById("t1").value;
x=Number(x);
var f=1;
for(var i=1;i<=x;i++)
f=f*i;
document.getElementById("result").value=f;
}

While loop


function f1()
{
var x=document.getElementById("t1").value;
x=Number(x);
var f=1;
var i=1;
while(i<=x)
{
f=f*i;
i++;
}
document.getElementById("result").value=f;
}

Do While


function f1()
{
var x=document.getElementById("t1").value;
x=Number(x);
var f=1;
var i=1;
do
{
f=f*i;
i++;
}
while(i<=x);
document.getElementById("result").value=f;
}

Leave a Reply