Let’s write a JavaScript program to print Even Numbers within a given range.
First, to find an Even number it is very simple, divide the number by 2 if the remainder is zero then it’s an Even number.
Example if you give the start and end range from 10 to 20, the program has to print 10, 12, 14, 16, 18, 20. So let’s write a simple snippet now.
1 2 3 4 5 6 7 8 |
for(i=10; i<=20; i++){ // let's divide the value by 2 // if the remainder is zero then it's an even number if(i % 2 == 0){ console.log(i); } } |
The above script should print the values in the console as expected.
Let’s write a dynamic script with HTML to get the start and end range from the user and print the output on the browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<html> <head> <title>JavaScript to print Even Numbers within a Range!</title> <script> function printEvenNums(){ //get the start and end range from user var start = parseInt(document.getElementById("start").value); var end = parseInt(document.getElementById("end").value); var evenNums = "<br>Even Numbers:<br>"; for(i=start; i<=end; i++){ // let's divide the value by 2 // if the reminder is zero then it's an Even number if(i % 2 == 0){ evenNums += i + "<br>"; } } //print the values document.getElementById("result").innerHTML = evenNums; } </script> </head> <body> <h3>JavaScript to print Even Numbers within a Range!</h3> Start: <input type="number" min="0" id="start" value="1" /> End: <input type="number" id="end" min="1" value="20" /> <input type="button" onclick="printEvenNums()" value="Print Even Numbers" /> <div id="result"></div> </body> </html> |
Just go through the above script to understand it.
You can also see the demo of the above script:
There’s a bug. When I enter 3 at start and 20 at the end. Program doesnt work. 4 and 30,5 and 40,….,don’t work. Help.
Thanks for noticing, Updated the code, Please check now.
hello can you please add a button to display the sum and average of the code