Home  >  Article  >  Web Front-end  >  How to find the sum from 1 to 100 in javascript

How to find the sum from 1 to 100 in javascript

藏色散人
藏色散人Original
2021-11-08 15:21:1217586browse

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>

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>

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!

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