Home > Article > Web Front-end > How to find the sum of odd numbers within 100 in javascript
In JavaScript, you can use for loops and if statements to find the sum of odd numbers within 100. The syntax "var sum=0;for (var i=1;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In javascript, we can use a for loop to find the sum of odd numbers within 100.
Implementation idea:
First use a for loop to control the range and traverse the numbers from 1 to 100
Then in the loop, use the if statement to determine whether the number i
is an odd number (whether i
can be divided by 2)
If it is an odd number, add sum =i
;
In this way, after the for loop ends, you will get an odd number and sum
Finally output the sum of odd numbers and sum
The implementation code for finding the sum of odd numbers within 100 is given below:
var sum = 0; for (var i = 1; i <= 100; i++) { if(i % 2 != 0){ sum+=i; } } console.log( "100内的奇数和: " + sum);
Output result:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to find the sum of odd numbers within 100 in javascript. For more information, please follow other related articles on the PHP Chinese website!