Home > Web Front-end > Front-end Q&A > How to add from 1 to n using javascript

How to add from 1 to n using javascript

青灯夜游
Release: 2022-02-08 12:04:12
Original
3119 people have browsed it

In JavaScript, you can use the for loop statement and the " " operator to implement the operation from 1 to n, the syntax is "var sum=0;for (var i=1; i

How to add from 1 to n using javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript implements adding from 1 to n

In javascript, if you want to add from 1 to n, you can use the for loop statement, just You need to add the traversed numbers in the loop body

for (var i = 1; i <= n; i++) {
sum = sum + i;
}
Copy after login

After the loop ends, the value of the variable sum is accumulated and the calculated result is output. It should be noted that the declaration and initialization of variable sum must be placed before the for loop, and the initialization value must be 0, so as not to affect the result of the addition operation.

The complete implementation code is given below:

function sum(n) {
	var sum=0; 
	for (var i=1;i<=n;i++){
		sum += i;
	}
	console.log(sum);
}
Copy after login

When n is a different value, the output results are also different:

sum(2);
sum(3);
sum(4);
sum(5);
sum(6);
Copy after login

How to add from 1 to n using javascript

【 Related recommendations: javascript learning tutorial

The above is the detailed content of How to add from 1 to n 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