+ 1

Help me figure this out. Thanks

var I, j; var c = 0; for (i =1; i <= 3; i++) { for (j = 1; j <= 2; j ++) { c += j; } } alert (c);

23rd Feb 2018, 6:05 PM
Briaה‎
2 odpowiedzi
+ 7
So the outer for loop starts with the value "i = 1" and then moves to the code inside it. The inner one starts at the value "j = 1" and then when c += j is run c has the value of 1 (c+= j means c = c + j which is c = 0 + 1 which is 1). j is then incremented and the inner for loop runs again so j = 2 and then c += j makes c = 3. After that j is more than 2 so the inner for loop is broken out of and the outer one starts again, now "i = 2" and the then inner one loops again so for "j = 1", c = c + j (c = 3 + 1), which is 4 and for "j = 2", c = 2 + 4, so c = 6 and now "j = 3" again which is more than 2, the inner loop is broken out of and the outer one is run over again with the value "i = 3". Moving into the inner loop again "j = 1" so c += j makes "c = 7" and then "j = 2" so c is now 9. Once again j is more than 2 so the inner loop is broken out of and now i is more than 3 so the outer loop is broken out of as well and move on the next statement the value of "c" is alert (9)
23rd Feb 2018, 6:27 PM
LynTon
LynTon - avatar
0
the outer loop will go 3 times and inside each the inner loop will go twice. so you add 1 and 2 3 times which is 3*3 =9
23rd Feb 2018, 6:58 PM
Dominique Abou Samah
Dominique Abou Samah - avatar