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....
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]);
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])
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))