Home > Web Front-end > JS Tutorial > How to find the sum of odd numbers within 100 in javascript

How to find the sum of odd numbers within 100 in javascript

青灯夜游
Release: 2023-01-07 11:47:14
Original
10440 people have browsed it

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

How to find the sum of odd numbers within 100 in javascript

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);
Copy after login

Output result:

How to find the sum of odd numbers within 100 in javascript

[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!

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