0
Need explanation... Can someone explain to me this code, step by step?
I understand what modulus is and how many iterations there are. But how does this code behave. What's the first step, second one and so on... var a=[9,5,3]; for (var i=1; i<3; i++) { a[0]%=a[i]; a[0]+=a[2]; } document.write (a[0]);
7 Answers
+ 8
You can divide the loop structure into four components:
1. initialization
2. checking condition
3. loop body
4. iteration
Now, for the given code, initial value for x is 1. The loop will stop if x becomes 5 or more.
x += x means, x = x+x
Also, before going to the next step each time, x will be x+1 because of the x++ part.
Detailed breakdown:
Step 1:
-----------
initial value: x = 1
condition: is x less than 5? Yes! So the loop body will be executed.
loop body: x = x+x = 1+1 = 2
iteration: x = x+1 = 2+1 = 3
Step 2:
----------
initial value: x = 3
condition: is x less than 5? Yes! So the loop body will be executed.
loop body: x = x+x = 3+3 = 6
iteration: x = x+1 = 6+1 = 7
Step 3:
----------
initial value: x =7
condition: is x less than 5? No :( So, execution will stop here. Loop body won't be executed.
Output: 7
Hope it helps :)
+ 7
a[0] %= a[i] is equivalent to a[0] = a[0] % a[i]
Same rule goes for += as well.
Breakdown:
Step 1:
i = 1
a[0] = a[0] % a[1] = 9%5 = 4
a[0] = a[0] + a[2] = 4+3 = 7
Step 2:
i=2
a[0] = a[0] % a[2] = 7% 3 = 1
a[0] = a[0] + a[2] = 1+3 = 4
Output: 4
+ 1
@Shamima Yasmin Thank you for your effort! Now I see.
+ 1
@Shamima Yasmin Well of course. Thanks a lot. This clears a lot. I must go through js loops lesson once more. Especially part about iterations.
I thought iteration is just for the loop to go to the next step until certain condition is met, not realising that it also adds one to the value because incrementation.
0
wow
0
@Shamima Yasmin Can you explain one more thing, like previous example by steps, but now this one?
var x=1;
for (; x<5; x++) {
x+=x;
}
output: ?
How come the answer is 7?
0
thanks