Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

299
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda