Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda