0
Can't understand the output.
This is a question in the js course.The correct answer is 16, but I can't understand how it's 16. It would be great if someone explained the solution. What is the output of this code? var sum=0; for(i=4; i<8; i++) { if (i == 6) { continue; } sum += i; } document.write(sum);
2 Respostas
+ 4
i starts off as 4. since i != 6, we add 4 to our total, which is now 4.
i is 5. since i != 6, we add 5 to our total, which is now 9.
i is 6. since i == 6, we end the loop right here and jump back up.
i is 7. since i != 6, we add 7 to our total, which is now 16.
i is 8, and our loop stops.
We print 16 onto the screen.
+ 1
var sum=0; This is used to intialize sum to 0
for(i=4; i<8; i++) {
if (i == 6) {
continue; This means that the the loop will skip the treatement when i=6
}
sum += i; This means that sum=sum+1 each time the loop is run
}
Now, we started with sum = 0 and i = 4
for i= 4 we will have sum = 4 by the end of the treatement
for i= 5, sum= 4+5 = 9
The loop won't sum for i=6 because we have the continue statement
for i= 7 we add 7 to the total which means sum = 9+7 = 16
document.write(sum); prints the result on the screen
Hope it helps !