Algorithm
-
Input: Accept a number as input.
-
Check Remainder: Divide the input number by 2.
-
Check for Zero Remainder:
- If the remainder is zero, the number is even.
- If the remainder is not zero, the number is odd.
-
Output:
- Display or return the result indicating whether the number is odd or even.
Code Examples
#1 Code Example- Using if...else
Code -
Javascript Programming
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is even
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is odd
else {
console.log("The number is odd.");
}
Copy The Code &
Try With Live Editor
Output
Enter a number: 27
The number is odd.
The number is odd.
#2 Code Example- Using Ternary Operator
Code -
Javascript Programming
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
// ternary operator
const result = (number % 2 == 0) ? "even" : "odd";
// display the result
console.log(`The number is ${result}.`);
Copy The Code &
Try With Live Editor
Output
Enter a number: 5
The number is odd.
The number is odd.
Demonstration
Javascript Programing Example to Check if a Number is Odd or Even-DevsEnv