Home how to use negative values in for loops

# how to use negative values in for loops

user8326
1#
user8326 Published in September 20, 2018, 10:22 pm

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++){
if(i%2!==0){
sum=sum+i
}
}
console.log(sum);


what is wrong with my code

• are you sure you understood the problem correctly? the sum of the odd negative numbers equally cancel out the sum of the positive odd numbers.. the answer is zero and your code works fine. – Occam's Razor Feb 13 at 2:21
• Well that seems right to me. lets do -4 to 4 ... -3 + -1 + 1 + 3 – epascarello Feb 13 at 2:22
• I'm voting to close this question as off-topic because there is absolutely nothing wrong with this code. – Occam's Razor Feb 13 at 2:22
• It's very funny. It's just a mathematic issue ^^ Not a code issue – Gilles Quenot Feb 13 at 2:24
• thanks for your time:) – iamlearning Feb 13 at 3:17