How can I make a sum of numbers in a for loop?

Viewed 29

How can I make a for-loop which calculates the sum of all numbers from 1 to 100 and continuously stores it in sum. That is the for loop must go from 1 to 100 inclusive?

let sum = 0;

for (let i = 0; i <= 100; i++) {
  sum = sum + i;
}

1 Answers

Your loop condition should be < instead of >= and within the loop you need to take the last value of sum and add i to it. Lastly, if you want the sum of numbers from 1 to 100, then your loop has to start at 1 and end at 100.

let sum = 0;

for (let i = 1; i < 101; i++) {
  sum = sum + i;
}

console.log(sum);

Related