Factorial of a Number using For Loop
In this tutorial, you are given a number. write a JavaScript program with a function that takes a number as argument, find the factorial of the number using for loop, and returns the result.
Solution
Initialise factorial
with 1
.
Inside for loop, iterate variable i
from 1
to n
, and multiply assign factorial
with i
.
After the loop is executed, factorial
contains the factorial of n
.
Program
In the following program, we find the factorial of a number in n
using for loop.
function findFactorial(n) {
var factorial = 1;
for (var i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}
var n = 5;
console.log(n+'! = '+ findFactorial(n));