Let’s write a JavaScript program to print Odd Numbers within a given range.
First, to find an Odd number it is very simple, divide the number by 2 if the remainder value is not zero then it’s an Odd number.
Example if you give the start and end range from 10 to 20, the program has to print 11, 13, 15, 17, 19. 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 not a zero then it's an odd 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 Odd Numbers within a Range!</title> <script> function printOddNums(){ //get the start and end range from user var start = document.getElementById("start").value; var end = document.getElementById("end").value; var oddNums = "<br>Odd Numbers:<br>"; for(i=start; i<=end; i++){ // let's divide the value by 2 // if the reminder is not a zero then it's an odd number if(i % 2 != 0){ oddNums += i + "<br>"; } } //print the values document.getElementById("result").innerHTML = oddNums; } </script> </head> <body> <h3>JavaScript to print Odd 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="printOddNums()" value="Print Odd 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: