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

121
Visualizações
How to iterate to 100 using a for or while loop and show the sum of each iteration with javascript?

Just doing a small homework. I need to iterate to 100, but also console.log the result of each previous example.

Example of the series: (1)+(1+2)+(1+2+3)+…+(1+2+3+…+n)<=100

Iteracion1=1
Iteracion2= 1+2 = 3
iteracion 3: 1+2+3 = 6
iteracion 4: 1+2+3+4 = 10

I have this:

for (i = 0; i <= 100; i++) {
    if(i < 100) {
    console.log(`${i}+${1}`);
   }};

But I don't know how to add the sum of it on each iteration. I you have any references for this it would be great! thank you.

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

0

You can efficiently achieve the result using a single loop.

For demo purposes, I've printed up to 20. You can add any number of your choice.

let lastTotal = 0;
let lastStr = "";

for (let i = 1; i <= 10; ++i) {
  const total = (lastTotal ?? 0) + i;
  const str = lastStr ? lastStr + " + " + i : i;
  console.log(`Iteration ${i}: ${str}${total === 1 ? "" : " = " + total}`);
  lastTotal = total;
  lastStr = str;
}
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

This should do fine.

I created a new Array for the length of iteration of i and use Array#reduce to sum it all up to a number.

const max = 10;

for (let i = 1; i <= max; i++) {
  const arr = new Array(i).fill().map((_, i) => i + 1);
  console.log(`Iteration ${i}: ${arr.join('+')} = ${arr.reduce((acc, b) => acc + b, 0)}`);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use variables outside of for to achieve this

let sum = 0;
const previousSums = [];
for (i = 0; i < 100; i++) {
  previousSums.push(sum);
  sum += i;
  console.log(`${previousSums}`);
}

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