0
Simple Javascript For Loop
Hey guys, i need to know if my thought process is correct for this for loop: function f(n) { var res=1; for(var i=2; i<= n ;i++){ res*=i; } return res; } document.write(f(4)); The result of f(4) is 24 and i thought it in this way: i = 2 2 <= 4 Yes res*=i -> res = res * i -> res = 1 * 2 = 2 i = 3 (because we increment i) 3 <=4 Yes res*=i -> res = res * i -> res = 1 * 3 = 3 i = 4 4 <= 4 Yes res*=i -> res = res * i -> res = 1 * 4 = 4 This is where the loop stop because the next time i=5 is not <= of 4 Now we have 3 different res result (2, 3 and 4) So for get the 24 final result you just multiply them like this 2*3*4 = 24? Is this the correct process?
2 odpowiedzi
+ 6
Not exactly:
i = 2
2 <= 4 Yes
res*=i -> res = res * i -> res = 1 * 2 = 2
Yes, but next, res now equals to 2:
i = 3 (because we increment i)
3 <=4 Yes
res*=i -> res = res * i -> res = 2 * 3 = 6
... and by same way:
i = 4
4 <= 4 Yes
res*=i -> res = res * i -> res = 6 * 4 = 24
This is where the loop stop because the next time i=5 is not <= of 4
Next is wrong:
Now we have 3 different res result (2, 3 and 4)
So for get the 24 final result you just multiply them like this 2*3*4 = 24?
Is this the correct process?
So you're near, but not ;)
I hope I've been clear ^^
+ 1
Oh damn i've not considered that the res value get updated on every cicle :-/
Thx visph