Introduction
Determining whether a number is even or odd is a basic and common operation in programming. A number is even if it is divisible by 2 with no remainder and odd if it leaves a remainder of 1 when divided by 2. This program will help check if a given number is even or odd.
Problem Statement
Create a JavaScript program that:
- Accepts a number.
- Checks whether the number is even or odd.
- Displays the result indicating if the number is even or odd.
Example:
Input:
12
Output:
12 is an even number
Input:
7
Output:
7 is an odd number
Solution Steps
- Read the Input Number: Accept the number either from user input or directly within the code.
- Check Even or Odd: Use the modulus operator (
%
) to determine if the number is divisible by 2. - Display the Result: Print whether the number is even or odd based on the result.
JavaScript Program
// JavaScript Program to Check if a Number is Even or Odd
// Author: https://www.javaguides.net/
function checkEvenOrOdd(number) {
// Step 1: Check if the number is even or odd
if (number % 2 === 0) {
console.log(`${number} is an even number`);
} else {
console.log(`${number} is an odd number`);
}
}
// Example input
let inputNumber = 12;
checkEvenOrOdd(inputNumber);
Output
12 is an even number
Example with Different Input
let inputNumber = 7;
checkEvenOrOdd(inputNumber);
Output:
7 is an odd number
Explanation
Step 1: Check if the Number is Even or Odd
- The number is passed to the
checkEvenOrOdd()
function. The modulus operator (%
) checks if there is any remainder when the number is divided by 2. If no remainder is left (number % 2 === 0
), the number is even; otherwise, it is odd.
Step 2: Display the Result
- The result is printed using
console.log()
, specifying whether the number is even or odd.
Conclusion
This JavaScript program demonstrates how to check whether a number is even or odd using the modulus (%
) operator. This simple task is essential for various logic operations in programming, helping developers handle conditional checks based on numerical properties.
Comments
Post a Comment
Leave Comment