Skip to main content

Exercise 19: Even Number Counter with a While Loop

Use while loops to count and print even numbers. Learn how to iterate with precise logic in your JavaScript programs.

The main goal is to learn how to use the while loop.whileto count numbers and make decisions.

Activity

  1. Use a loopwhile1. Count the even numbers between 1 and 20.

  2. Each time you find an even number, display the number on the console.

  3. End the loop when you reach the number 20.

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>Contador de números pares con while</title>
</head>
<body>
<h1>Ejercicio 19: Contador de números pares con while</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 numero = 1;

while (numero <= 20) {
if (numero % 2 === 0) {
console.log(numero);
}
numero++;
}
info

🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.