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