SamB. SamB. - 21 days ago 4x
HTML Question

For Loop, while Limit is a Negative Number

I am relatively new to programming and I am taking a Web programming course in my University studies. Using JavaScript, we are to write a for loop that, will compute the total of all integers from 0 up to, and including, the limit.

I was able to get all integers from 0 and above to successfully work, however, when I enter a negative integer (-3 for instance) the function does not return a total of 0 as it should. I simply returns nothing at all. I will include my JavaScript code below. If anyone has some tips to help out, I would greatly appreciate it!

document.getElementById('go').onclick = function () {
var limit = document.getElementById('limit').value;
var total = 0;
for (i = 0; i <= limit; i ++) {
total = total + i;
document.getElementById('total').value = total;


Your output, document.getElementById('total').value = total; is inside loop.

Move it outside of loop or it won't be executed (and nothing will show up)

Loop is executed 0 times, so this line in this loop is executed 0 times too.