Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds with JavaScript Loops

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading