Home > Web Front-end > JS Tutorial > body text

How to find the sum from 1 to 100 in javascript

藏色散人
Release: 2021-11-08 15:21:12
Original
17510 people have browsed it

Javascript method to find the sum from 1 to 100: 1. Create an HTML sample file and add a script tag; 2. Use "for(i=1;i<=100;i){sum=sum i }" statement can be used to find the sum from 1 to 100.

How to find the sum from 1 to 100 in javascript

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

How to find the sum from 1 to 100 in javascript?

very simple!

The js code is as follows:

<script>
    var sum=0;
for(i=1;i<=100;i++){
    sum=sum+i
}
document.write(sum);
//计算结果是5050
</script>
Copy after login

Run this code to get the cumulative sum from 1 to 100, 1 2 3 4... 100=5050.

We also The sum requirement can be encapsulated into a function, the code is as follows:

<script>
function add(start,end){
    var sum=0;
    for(i=start;i<=end;i++){
        sum=sum+i
    }
return sum;
 
}
document.write(add(1,100));
</script>
Copy after login

The running result is still 5050.

Video tutorial recommendation: "javascript basic tutorial"

The above is the detailed content of How to find the sum from 1 to 100 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!