Ruben
Ruben

Reputation: 955

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.

Upvotes: 2

Views: 3827

Answers (5)

Shravan Kumar
Shravan Kumar

Reputation: 1

var total = 0;
var res = 0;
var upto = 6;
for(i=1;i<=upto;i++){
total = total+i;
res = res+total;
}
console.log(res);

Upvotes: 0

DecPK
DecPK

Reputation: 25406

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; }

Upvotes: 2

a.mola
a.mola

Reputation: 4011

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)}`);
}

Upvotes: 0

Andy
Andy

Reputation: 63579

  1. Create an array you can add indexes to.

  2. Create a function that calculates the sum of the numbers in the array. I've used reduce here.

  3. Create a string, and then log it.

const arr = [];

function sum(arr) {
  return arr.reduce((acc, c) => acc + c, 0);
}

// On each iteration push the index in to the
// array. Create a string that joins up the array
// elements and logs the result of the sum
for (let i = 1; i <= 10; i++) {
  arr.push(i);
  const str = `Iteration ${i}: ${arr.join('+')} = ${sum(arr)}`;
  console.log(str);
};

Upvotes: 0

ostapyrih
ostapyrih

Reputation: 79

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}`);
}

Upvotes: 0

Related Questions