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

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

青灯夜游
Release: 2022-01-21 17:56:25
Original
8416 people have browsed it

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++) {
}
Copy after login

In the loop body, just add the traversed numbers. There are two ways to write them (just choose one):

sum += i;
//或
sum = sum + i;
Copy after login

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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template