'Sum of odd numbers until reached limit in Javascript

While I was solving a question saying "add odd numbers from 1 to 20", I coded this:

var i, sum=0;
for (i=2; i<=20; i*2){
  sum=sum+i;
}
document.write(sum);

When I launched it through a browser, it did not work. However, when I fixed i*2 into i+=2, it worked.

What am I missing? Am I not able to use *(multiplier) in For Loops?



Solution 1:[1]

If you need to add odd numbers from 1 to 20, then you need i+=2 as the third parameter of the for and need to initialize the variable to 1 to get the correct result:

var sum = 0;
for (var i = 1; i <= 20; i += 2) {
    sum += i;
}

When you have

i += 2

2 is added to i and the result is stored into i. When you tried

var i, sum=0;
for (i=2; i<=20; i*2){
  sum=sum+i;
}

i*2 calculates the value which is twice as big as i, but it will not change the value of i, so this would "work" instead:

var i, sum=0;
for (i=2; i<=20; i*=2){
  sum=sum+i;
}

where

i *= 2

not only calculates the value twice as big as i, but stores the result into i as well. However, even though this will run, the result will not be correct, since you are using the wrong formula.

Also, you can calculate the result without using a for:

1 + 2 + ... + n = n * (n + 1) / 2

Assuming that n is pair: and since we know that we are "missing" half the numbers and all the pair numbers are bigger exactly with 1 than the previous impair numbers, we can subtract half of the sequence

n * (n + 1) / 2 - n / 2 = (n * (n + 1) - n) / 2 = (n * (n + 1 - 1)) / 2 = n * n / 2

and now we have exactly the double value of what we need, so the final formula is:

sum = n * n / 4;

Let's make this a function

function getOddSumUpTo(limit) {
    if (limit % 2) limit ++;
    return limit * limit / 4;
}

and then:

var sum = getOddSumUpTo(20);

Note that we increment limit if it is odd.

Solution 2:[2]

The issue is that you're not updating the value of the i in the for loop.

I want add odd numbers from 1 to 20

Then you need to change the initial value of i to 1.

var i, sum = 0;
for (i = 1; i <= 20; i += 2){
  sum += i;
}
document.write(sum);

Also, you can find the sum of odd numbers from 1 to 20 by using a formula.

n = 20;
console.log(n % 2 == 0 ? (n * n)/ 4 : ((n + 1) * (n + 1))/4);

Solution 3:[3]

You can you just have to do it simillary to what you've written about sum.

You used there i += 2 and not i + 2.

The same way just change i * 2 to i *= 2.

Here is an working example

var i, sum = 0;
for (i = 2; i <= 20; i *= 2) {
  console.log(i);
  sum += i;
}
document.write(sum);

But a couple of things here.

First of all you wrote

add odd numbers from 1 to 20

and in all your examples you use sum on even numbers.

Secondly, by multiplying you will not achieve your desired goal (as you can see in a snippet above in a console)

So to actually

add odd numbers from 1 to 20

you should do it like this:

var i, sum = 0;
for (i = 1; i <= 20; i += 2) {
  console.log(i);
  sum += i;
}
document.write(sum);

EDIT

If you want to add even numbers you still can't use multiplying.

Why? Simply because you said yourself that you want a sum of numbers.

So let's say that we start with 2.
If we multiply it by 2 it has the value 4 which is fine.
But now look what happens in the next iteration. Our variable i which has the value 4 is multiplied by 2 and now its new value is 8. So what about 6?
Next iteration multiply 8 by 2 and its new value is 16.

Do you see where this is going?

And when you use i += 2 instead of i *= 2?

So if we start with 2 and than we add 2 its new value is 4.
In next iteration we add 2 to 4 and we have 6.
And so on.

If you want to test it, here is an example with multiplying and adding.

Pay attention to console logs

var i;

console.log("Multiplying");
for (i = 2; i <= 20; i *= 2) {
  console.log("i value is: " + i);
}

console.log("Adding");
for (i = 2; i <= 20; i += 2) {
  console.log("i value is: " + i);
}

Solution 4:[4]

What you are looking is this :

let sum = 0;
for(var i = 2; i <= 20; i += 2){
  sum += i;
}
document.write(sum)

Another take on this :

// set to n (what you want). Set to n + 1
var N = 21;

// The main driver code create an array from 0-(N-1) and removes all even nums

let a = Array.apply(null, {length: N}).map(Number.call, _ => +_).filter(_=>_%2)

// console.log the array
console.log(a)

Solution 5:[5]

You can use whatever expression in loop header, even this is a valid for loop statement for (;;) which simply runs forever (equivalent to while(true)).

Problem is that you are not updating the i counter in for (i=2; i<=20; i*2) so the i will stays the same throughout the execution of the loop. If you change it to for (i=2; i<=20; i = i*2) or for (i=2; i<=20; i *=2) then it will work.

It is the same as if you did

let i = 1;

i * 2;
console.log(i);

i = i * 2;
console.log(i);

The first i * 2 doesn't update the i while the second one does.

You can also translate the for loop into while loop to see the error more clearly.

// wrong
let i = 1;
while(i <= 20) {
  i * 2;
  // do something
}

// right
let i = 1;
while(i <= 20) {
  i = i * 2 // or i *= 2
  // do something
}

Just a side note, if you wanted to perform sum on more types of sequences efficiently than you could use a generator based approach and write your sum function and describe each type of a sequence with a generator function.

function *generateOdd(start, end) {
  for (let i = start; i <= end; i++) {
    if (i % 2 === 1) { yield i; }
  }
}

function *generateEven(start, end) {
  for (let i = start; i <= end; i++) {
    if (i % 2 === 0) { yield i; }
  }
}

function sumNums(gen, start, end) {
  const generator = gen(start, end);
  let res = 0;

  let item = generator.next();
  while (!item.done) {
    res += item.value;
    item = generator.next();
  }

  return res;
}

console.log(sumNums(generateOdd, 0, 20));
console.log(sumNums(generateEven, 0, 20));

Solution 6:[6]

/* sum of the Odd number using loop */
function sumOfOddNumbers(n){
  let sum= 0;
  for(let i = 1; i <= n; i++) {
      if(i % 2 !== 0){
        sum = sum + i;
      }    
  }
  return sum;
}

// 567 = 1+3+5+7+9+11+13+15+17+19+21+23+25+27+29+31+33+35+37+39+41+43+45+47
let n = 47;
let sum = sumOfOddNumbers(47);
alert('sumOfOddNumbers(' + n + ') = ' + sum);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 Muhammad Salman
Solution 5
Solution 6 Mass Dot Net