Find the sum of all multiples of 2 less than 10000

We are finding all the multiples of 2 less than 10000 so first it's a good idea to iterate over 10000.
For this we use a loop such as a for loop to check each number from 0 to 10000.
Then we need to check if the number we are iterating over is a multiple of 2. For this we need an if statement. One way to find a multiple of 2 is to use the modulus operator '%'. The modulus evaluates the remainder of two numbers for example 4 % 2 would evaluate to 0 as there is no remainder. This can be used to find the numbers that are multiples of 2. 
Finally we need to sum these multiples. To store the sum we need to create a variable. Every time a number we are iterating over satisifies our if condition we must add it on top of whatever is already stored in our sum variable.
The final code might look something like this:
var sum = 0, i
for (i = 0; i < 10000; i++) {
   if (i % 2 == 0) {
    sum = sum + i
 }
}
 
console.log(sum)
N.b notice that in standard js syntax no semicolons are used as line terminators and indentation is two spaces.

TB
Answered by Tom B. Javascript tutor

2528 Views

See similar Javascript Mentoring tutors

Related Javascript Mentoring answers

All answers ▸

Suppose that you have a <p> element with an id of 'id1'. Use javascript to set the inner html of this element to 'hello!'


How do you create objects in javascript?


How are objects created in arrays


I've just heard about objects. How do I use them and do they work with Arrays?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences