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

210
Visualizações
How to store and print out a sum that's in a for loop?

The program is this: Insert a number, for example 5 and add it with all numbers below it. In this case, it would be 5+4+3+2+1=15

I have this:

var res = 0

function addUp3(num) {
  for (var i = 0; i <= num; i++) {
    console.log(i);
    res += i;
    console.log(res);
  }
}

I have no clue why it prints out random numbers.

The output of this was: 0,0,1,1,2,3,3,6 (without commas)

I've tried looking for an answer online, but they all want to do it with arrays, I don't think it's neccesary to do so. Can someone open my mind a bit please.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I moved the final print of res out of the loop and started the loop at 1 instead of 0

var res = 0

function addUp3(num) {
  for (var i = 1; i <= num; i++) {
    console.log(i);
    res += i;
  }
  console.log(`sum: ${res}`);
}

addUp3(5);

about 4 years ago · Juan Pablo Isaza Relatório

0

The for loop adds i each time. 0 + 1 + 2 + ... n. The reason it's printing twice is because you have 2 console.logs.

  1. Log 1 prints 0 (i)
  2. Log 2 prints 0 (res + i)
  3. Log 3 prints 1 (i)
  4. Log 4 prints 1 (res + i)
  5. Log 5 prints 2 (i)
  6. Log 6 prints 3 (res + i, which here would be 1 + 2)

If you just want the final answer, have a console.log(res) after your for loop

var res = 0

function addUp3(num) {
  for (var i = 0; i <= num; i++) {
    res += i;
  }
  console.log(res)
}
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