Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!