Exercise 21: Adding Even Numbers in a Range with JavaScript
Learn to create a JavaScript script that iterates through a range of numbers and adds only the even numbers. Strengthen your skills with loops and conditional structures. The main goal is to learn how to use loops.forto sum even numbers within a specified range.
Activity
-
Ask the user to enter a number that represents the end of a range (for example, 10 to get the even numbers between 1 and 10).
-
Use a loop
forTo iterate from 1 up to the entered number. -
In each iteration, check if the current number is even.
-
If it is even, add it to a variable that stores the total.
-
At the end of the loop, display the sum of all the even numbers found in the range.
Solution
Step 1: Create the index.html file
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sumar números pares en un rango</title>
</head>
<body>
<h1>Ejercicio 21: Sumar números pares en un rango</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
JavaScript
let numeroFinal = parseInt(prompt("Ingresa un número final para el rango:"));
let sumaPares = 0;
for (let i = 1; i <= numeroFinal; i++) {
if (i % 2 === 0) {
sumaPares += i;
}
}
console.log(
`La suma de todos los números pares entre 1 y ${numeroFinal} es: ${sumaPares}`,
);
info
🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.