how to use negative values in for loops

i am trying to get the sum of odd numbers with values starting from -300,000 to 300,000 and i am getting my result as ZERO can anybody help why?

var sum=0;
for(var i= -300000;i<=300000;i++){

what is wrong with my code

1 answer

  • answered 2018-02-13 02:19 Gilles Quenot

    Try this simplified code (with a bit a debug) to understand that there's just a math issue :

    for (var i= -30;i<=30;i++){
        console.log('i == ' + i);
        if (i%2!==0) {
            console.log('sum is now ' + sum);