Home  >  Article  >  Web Front-end  >  How to find the cumulative sum from 1 to 100 using javascript

How to find the cumulative sum from 1 to 100 using javascript

青灯夜游
青灯夜游Original
2022-01-21 17:56:258358browse

Method: 1. Use the "for (var i=1;i

How to find the cumulative sum from 1 to 100 using javascript

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

How to find the cumulative sum from 1 to 100 using javascript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn