Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
iterating from 0 to 100 and printing the sum of all evens and the sum of all odds as array

I am trying to iterate from 0 to 100 and trying to print the sum of even numbers and odd numbers as array, like this [2550, 2500].

let m=0;

for(let i=0;i<=100;i++) { 
  m = m + i;
}

console.log(Array.from(String(m)));

but this code is returning  ['2', '5', '0', '0']

Can anyone please show me how can I print both the sums as array?

Also if someone could help me with the code for putting this code into other conditional statement so that I can get both, the sum of odd numbers and sum of even numbers. I am facing issue deciding which one to use here, else if, if else....

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You just need to check the reminder of the number(i), if it's zero then it is even else it's odd.

let m=0,k=0;
for(let i=0;i<=100;i++)
{ 
if(i%2==0)m+=i
    else k+=i;
}

then console.log([m,k]);

about 4 years ago · Juan Pablo Isaza Report

0

Your code is calculating the sum of all the numbers in the range of 0-100.

m will have the sum of range(0-100) that is 5050.

for(let i=0;i<=100;i++) { 
  m = m + i;
}

This line will split the digits of variable m and make an array of it.

console.log(Array.from(String(m)));

['5','0','5','0']

You can have two variables for even_sum and odd_sum and then check if i is odd then add it to even_sum else add it to `odd_sum'.

let even_sum=0;
let odd_sum=0;

for(let i=0;i<=100;i++) { 
    if (i%2==0)
        even_sum+=i;
    else
        odd_sum+=i;
}

To return the values as array, you can do -

console.log([even_sum,odd_sum])
about 4 years ago · Juan Pablo Isaza Report

0

As you tagged the question with math I think the mathematics of triangular numbers should be mentioned here:

function sumOddEven(n) {
    const floor = Math.floor(n / 2);
    const ceil = Math.ceil(n / 2);
    return [ceil * ceil, floor * (1 + floor)];
}

console.log(sumOddEven(100))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!