Home > Mobile >  Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds with Ja
Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds with Ja

Time:02-20

I'm trying to answer for this question: "Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds."

and my code is:


numbersE = []
numbersO = []
let sumE = 0
let sumO = 0


for (i=0;i<=100;i  ) {

    if(i % 2 == 0){
        numbersE.push(i)
     }

    else {
        numbersO.push(i)
        
    }
    
    sumE  = numbersE[i]
    sumO  = numbersO[i]
}

console.log(sumE, sumO)

Nan Nan

where is the my mistake ?

CodePudding user response:

Let's start with the loop. At i=0, if statement is triggered and 0 is pushed to the array numbersE and hence sumE = 0. But the array numbersO is empty because the for loop didn't push any values to numbersO. Therefore at i=0, sumO returns NaN.

This can be solved by:


let i;
let sumE = 0;
let sumO = 0;

for (i = 0; i <= 10; i  ) {
  i % 2 === 0 ? (sumE  = i) : (sumO  = 1);
}

console.log(sumE, sumO);

CodePudding user response:

let sumE = 0
let sumO = 0

// You could technically start at 1 here
for (let i = 0; i <= 100; i  ) {
  // Just add the numbers without using arrays
  if (i % 2 == 0) {
    sumE  = i
  } else {
    sumO  = i
  }
}

console.log(sumE, sumO)

  • Related