Search code examples
javascriptfactorial

Finding the factorial using a loop in javascript


I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.

How can I stop i reaching inputNumber?

var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 0; i <= inputNumber; i++){
    total = total * (inputNumber - i);
}

console.log(inputNumber + '! = ' + total);

Solution

  • here is an error i <= inputNumber

    should be i < inputNumber

    var inputNumber = prompt('Please enter an integer');
    var total = 1;
    
    for (i = 0; i < inputNumber; i++){
        total = total * (inputNumber - i);
    }
    
    console.log(inputNumber + '! = ' + total);