Computer Science, asked by vishalmandal6493, 4 days ago

Evaluate n! (ex. 5! = 5 * 4 * 3 * 2 ) where n is entered by the user. in Javascript

Answers

Answered by amproc
1

Answer:

function factorial(n) {

     var buffer = n;

     for (var iterator = n-1; iterator > 1;iterator--) {

          buffer = buffer * iterator

     }

     return buffer;

}

var input = 5; // varying value, taking 5 just for example

console.log(factorial(input))

Explanation:

The calculation is done through a factorial() function. Inside the function, a temporary variable buffer is declared to store the return value and its value is set to the parameter n

The buffer variable is then modified (multiplied) by the iterator inside the decrementing loop. Finally, the value of the buffer variable is returned where the log function prints the returned value.

Similar questions