This is another interesting program for school / college students who are learning JavaScript.
To find an entered number is Odd or Even is very simple, all you have to do is divide the number by 2 and if you get the remainder 0 (zero) then it is an Even number otherwise an Odd number.
Eg: 10 / 2 = 5, here 5 is the quotient, 0 is the remainder.
In JavaScript there are two operators you can use to find quotient and remainder. (/) slash and (%) modulus, where the / will give the quotient and % will give the remainder value.
So here is the JavaScript snippet:
1 2 3 4 5 |
if ( num % 2 == 0) { alert('Even Number'); }else{ alert('Odd Number'); } |
For better understanding I am giving here a full example :
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 |
<!DOCTYPE html> <html> <head> <title>JavaScript to find Odd or Even number Example - Tutorialsmade.com!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function findOddEven(){ //get the input value var num = document.getElementById('num').value; //if the remainder value is 0 then it is an even number //we are using % modulus operator to get the remainder value if ( num % 2 == 0) { document.getElementById('result').innerHTML = num + ' is an Even number'; }else{ document.getElementById('result').innerHTML = num + ' is an Odd number'; } } </script> </head> <body> <h2>JavaScript to find Odd or Even number!</h2> <form method="post"> Enter a number: <input type="number" id="num" name="num" min="0" /><input type="button" value="Find Odd or Even" onclick="findOddEven()" name="find" /> <div style="margin-top: 10px;" id="result"></div> </form> </body> </html> |
And as always your demo:
Thank you.
function oddOrEven(number_){
if(number_ % 2 === 0){
return ‘even’;
};
return ‘odd’;
};
life saver!!!!!!!!!!!!!!