- 1
Please explain this code.. how does "sum" assign its value from " i" in this code below ?
//i checked its value and it is 14 but how did it get its value ? //code var sum = 0; for(var i=1;i<=9;i++){ if(i%5===0||i%3===0){ sum+=i; } } document.write(sum); // executes 23
2 Respostas
0
Here's a line-by-line of what the for loop is doing. If you're expecting 14, you may want to change the condition in the for loop to be "i<9" as opposed to "i<=9", that way it will execute 8 times instead of 9
i=1, if statement is false, sum=0 (no change)
i=2, if statement is false, sum=0 (no change)
i=3, if statement is true, sum=0+3=3
i=4, if statement is false, sum=3 (no change)
i=5, if statement is true, sum=3+5=8
i=6, if statement is true, sum=8+6=14
i=7, if statement is false, sum=14 (no change)
i=8, if statement is false, sum=14 (no change)
i=9, if statement is true, sum=14+9=23
writes 23
Hope this helps!
+ 2
kenny@ , thank you ...👍😊
i got that now ......