javescript program that adds all even integers between 1 to 100

Dani AI

Generated

asked for a JavaScript program to sum all even integers from 1 to 100. The cleanest approach uses the arithmetic progression formula (no loop): the evens are 2..100 (50 terms), so the sum is 2550.

A small, reusable function that applies the formula for any integer range:

function sumEven(min, max) {
  const first = (min % 2 === 0) ? min : min + 1;
  const last  = (max % 2 === 0) ? max : max - 1;
  if (first > last) return 0;
  const n = ((last - first) / 2) + 1;
  return n * (first + last) / 2;
}

// example
// sumEven(1, 100) -> 2550

If readability is preferred over constant-time performance, an array+reduce approach is concise and expressive (but allocates an array):

const sum = Array.from({ length: ((100 - 2) / 2) + 1 }, (_, i) => 2 + i * 2)
                 .reduce((a, b) => a + b, 0);

Note about the earlier reply from : that quick solution will work, but avoid creating implicit globals by leaving variables undeclared. Use let/const and consider "use strict" to catch accidental globals (see the MDN strict-mode guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). For learning and reliable reference material, the MDN JavaScript guide is recommended: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide.

Recommended Answers

All 5 Replies

Its better you start learning basics of Javascript from w3schools coz this is a very easy program.

thank you its just that i dnt have enough time to do so thats why i asked for help

thank you its just that i dnt have enough time to do so thats why i asked for help

As you do not have time, i am giving you tha code but please, asking for code will nto work every time. You will have to learn the language.

count = 0;
for(i=0;i<=100;i+=2)
count+=i;
alert(count);

thank you
god bless :D

wep surely i will learn it as its a need

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.