Home >Web Front-end >Front-end Q&A >How to find the cumulative sum from 1 to 100 using javascript
Method: 1. Use the "for (var i=1;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Use javascript to add up from 1 to 100
In javascript, if you want to add up from 1 to 100, you can use a for loop statement
Use a for loop to traverse 1 to 100
for (var i = 1; i <= 100; i++) { }
In the loop body, just add the traversed numbers. There are two ways to write them (just choose one):
sum += i; //或 sum = sum + i;
After the loop ends, the value of variable sum will be the cumulative value from 1 to 100, and then output it.
The complete implementation code is given below:
function sum(n) { var sum=0; for (var i=1;i<=n;i++){ sum += i; } return sum; } console.log("1到100的累加为:"+sum(100));
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to find the cumulative sum from 1 to 100 using javascript. For more information, please follow other related articles on the PHP Chinese website!