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

140
Visualizações
How to sum up all numbers entered in prompt

var num = prompt("Enter a number");

for (var sum = 0; sum <= num; sum++) {
  sum = sum + 1;
}
document.write(sum);

example when I enter 6 in the prompt it will sum 1+2+3+4+5+6 =21. but as of right now i can only print 123456 instead of 21.

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

0

The problem with your code is that you're using sum for the loop and for the answer. That's messing everything up. You can use a variable for the loop and another variable for the sum.

Maybe that works for you.

var num = prompt("Enter a number");
var sum = 0;
for(var i = 1; i <= num; i++) {
    sum += i;
}
document.write(sum);

about 4 years ago · Juan Pablo Isaza Relatório

0

  • Input received by you is a string and that's why it's contacting rather than adding to sum.

  • This is the best optimum solution as its time complexity is O(3) times only.

  • so, it's fast. rather than with brute force which is o(n);

var num = prompt("Enter a number");

function total(n) {
  return n * (n + 1) / 2;
}
document.write(total(parseInt(num)));

about 4 years ago · Juan Pablo Isaza Relatório

0

here is some change in your code.
note: (+) is used to convert string-number type to number type

var num = prompt("Enter a number");
const sum = Array.from(Array(+num + 1).keys()).reduce((prev, curr) => prev += curr, 0);
document.write(sum);

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