Home  >  Article  >  Web Front-end  >  How to add from 1 to n using javascript

How to add from 1 to n using javascript

青灯夜游
青灯夜游Original
2022-02-08 12:03:433080browse

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

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

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

sum(2);
sum(3);
sum(4);
sum(5);
sum(6);

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!

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