JavaScript is one of mostly used scripting language all over the world. Today in this post we are going to see how to write a program to print Factorial values of a number using plain JavaScript.
Lets’ see the example (Find Factorial of a number using JavaScript):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<!DOCTYPE Html> <html> <head> <title>Find factorial of a number using Javascript</title> <script type="text/javascript"> function findFactorial(){ //clear the result div document.getElementById("result").innerHTML = ""; var num = document.getElementById("number").value; var fact = 1; //loop till the iterator i equals to number for (i = 1; i <= num; i++){ //formula to calculate factorial is to //multiply the iterator i value with fact value. fact = fact * i; //put the below lines of code out of this 'for loop' to show only the total value document.getElementById("result").insertAdjacentHTML('beforeend', '<br>'); document.getElementById("result").insertAdjacentHTML('beforeend', fact); } } </script> </head> <body> <h2>Find factorial of a number using Javascript</h2> Enter Number: <input type="number" id="number" min="1" max="100" /><button onclick="findFactorial()">Calculate</button> <div id="result"></div> </body> </html> |
Output of the above program will be something like this:
You can see the demo of the above script here: