Home > Web Front-end > JS Tutorial > How to find the sum of 1-n in javascript

How to find the sum of 1-n in javascript

青灯夜游
Release: 2022-01-18 18:47:58
Original
5633 people have browsed it

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

How to find the sum of 1-n in javascript

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

Javascript finds the sum of 1-n

If you want to find the sum of 1-n, you need to traverse the numbers 1~n, so for The initial condition of the loop can be set to i = 1, and the restriction condition can be i

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

Then in the loop body "{}", add the i values ​​of each loop. This requires an intermediate quantity sum to store the calculated value. The initial value of the variable sum must be 0, so as not to affect the result. There are two ways to write it (just choose one):

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

After the loop ends, the value of variable sum will be the sum of 1-n, 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 = sum + i;                    //将i+n的值给到sum
    }
    return sum;                       //返回sum值
}
console.log(sum(2));                //控制台输出1-2数和
console.log(sum(3));                //控制台输出1-3数和
console.log(sum(4));                //控制台输出1-4数和
console.log(sum(5));                //控制台输出1-5数和
console.log(sum(6));                //控制台输出1-6数和
console.log(sum(7));                //控制台输出1-7数和
console.log(sum(8));                //控制台输出1-8数和
console.log(sum(9));                //控制台输出1-9数和
console.log(sum(10));                //控制台输出1-10数和
Copy after login

How to find the sum of 1-n in javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to find the sum of 1-n in 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