Factorial Program in JavaScript using While Loop

To find factorial of a number, we need to multiply backward consecutive numbers till 1 starting from that number. We represent factorial with ! symbol.

For example, 4 factorial is written as 4! = 4 x 3 x 2 x 1

In this example, we’ll write a factorial program in JavaScript using a while loop.

To find the factorial of a number using while loop, all we need to iterate the loop starting from 1 till the number that is given. Whether we do iterate 1 to n or n to 1 doesn’t matter.

The logic would be as follows where num is the number to which we need to find factorial.

var fact = 1, i = 1;

while(i <= num) {
	fact = fact * i;
	i++;
}

At the end of this code we get the factorial of that number in fact variable.

Now, let us see a full working example along with simple html code.

<!DOCTYPE html>
<html>
<body>

<h2>Find Factorial</h2>
<input type="text" id="num"/>
<input type="button" value="Factorial" onclick="factorial()"/>


<div id="answer"></div>

<script language="javascript">

function factorial() {

var num = document.getElementById("num").value;
var fact = 1, i = 1;

while(i <= num) {
	fact = fact * i;
	i++;
}

document.getElementById("answer").innerHTML = fact;
}
</script>

</body>
</html>

Leave a Comment