简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM