Algorithm


  1. Input: Accept a number as input.

  2. Check Remainder: Divide the input number by 2.

  3. Check for Zero Remainder:

    • If the remainder is zero, the number is even.
    • If the remainder is not zero, the number is odd.
  4. 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

x
+
cmd
Enter a number: 27
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

x
+
cmd
Enter a number: 5
The number is odd.
Advertisements

Demonstration


Javascript Programing Example to Check if a Number is Odd or Even-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way