In this program, the user will take input through the window prompt and find the factorial numbers in JavaScript.
factorial of a number is the multiplication of all its below number. for example: 5! = 5*4*3*2*1 = 120this program will find factorial of numbers by using for loop
<!DOCTYPE html>
<html>
<body>
<script>
function factorial()
{
var fact=1,i;
var a=prompt("enter a number:");
for(i=1;i<=a;i++)
{
fact=fact*i;
}
document.write("factorial of number "+a+" is:",fact);
}
</script>
<form>
<input type="button" value="factorial" onclick="factorial();">
</form>
</body>
</html>
Input has taken through javascript prompt method
enter a number: 4 factorial of number 4 is:24
fact
variable with initialization value 1.a
.a
,fact=fact*i;
fact
variable, after the loop end print the factorial value.In this example, you will take input from the user by using window prompt method, and find the factorial of number using the while loop.
<!DOCTYPE html>
<html>
<body>
<script>
function factorial()
{
var fact=1,i=1;
// take input from user using prompt
var a=prompt("enter a number:");
while(i<=a)
{
// calculate factorial of number
fact=fact*i;
i++;
}
// print the factorial value
document.write("factorial of number "+a+" is:",fact);
}
</script>
<form>
<input type="button" value="factorial" title="calculate factorial" onclick="factorial();">
</form>
</body>
</html>
Input has been taken through the javascript prompt method
enter a number: 5 factorial of number 5 is:120
In this example, you will take number from the user by using window prompt method, and find the factorial of number by using the do while loop.
<!DOCTYPE html>
<html>
<body>
<script>
function factorial()
{
var fact=1,i=1;
// take input from user
var a=prompt("enter a number:");
do
{
// calculate factorial
fact=fact*i;
i++;
}while(i<=a);
// print factorial value
document.write("factorial of number "+a+" is:",fact);
}
</script>
<form>
<input type="button" value="factorial" onclick="factorial();">
</form>
</body>
</html>
Input has been taken through the javascript prompt method
enter a number: 3 factorial of number 3 is:6