The for cycle in javascript, can you alter variables?

2

I have a question, I found the following code to calculate the factorial number of a whole number, but I am doing my desktop run and I can not understand the code because it is assumed that in the process of the factorial it multiplies by all the numbers that are given before the number to be calculated, and the only answer that I find to the following code is that in the variable "result" I will store the value of the multiplication and that multiplies it by "i" up to 5 and there the cycle ends, but I'm not sure if what I think is correct, I leave the code and I hope you can help this neophyte.

var numero = prompt("Introduce un número y se mostrará su factorial");
var resultado = 1;

for(var i=1; i<=numero; i++) {
  resultado *= i;
}
alert(resultado);
    
asked by Jonathan Rivera Diaz 06.04.2017 в 21:36
source

1 answer

4

As you said, it is the multiplication of the numbers that precede it.

Ex:

5! = 5 * 4 * 3 * 2 * 1

But it's exactly the same as doing multiplication the other way

1 * 2 * 3 * 4 * 5 = 5!

Therefore

var numero = prompt("Introduce un número y se mostrará su factorial");
var resultado = 1;

for(var i=1; i<=numero; i++) {
  resultado *= i;
}
alert(resultado);

And taking this as a limitation:

It is understood that what is multiplying is from 1 to n, with the result. It's worth saying:

resultado = 1 * resultado;

resultado = 2 * resultado;

resultado = 3 * resultado;

resultado = 4 * resultado;

hasta. . .

resultado = n * resultado;

And as you said it was saved in the result variable, then once the cycle is finished, it appears in an alert.

I hope you understand the concept. Greetings !!!

    
answered by 06.04.2017 / 22:07
source