1. Introduction
Determining if a number is odd or even is a fundamental programming task that is often used in a variety of applications. TypeScript, being a superset of JavaScript, provides us with the tools necessary to accomplish this task effectively.
2. Program Overview
This program will contain a function named checkOddEven which will take a number as its parameter. It will return a string stating whether the number is 'Odd' or 'Even'.
3. Code Program
// Define the function with TypeScript type annotations
function checkOddEven(num: number): string {
if (num % 2 === 0) {
return 'Even';
} else {
return 'Odd';
}
}
// Test the function
const numberToCheck = 8;
const result = checkOddEven(numberToCheck);
console.log(`${numberToCheck} is an ${result} number.`);
Output:
8 is an Even number.
4. Step By Step Explanation
We use the modulus operator (%) to find the remainder of the division of the number by 2. If a number is divisible by 2 with no remainder (i.e., the remainder is 0), then it's an even number.
For our example:
8 divided by 2 = 4 with a remainder of 0.
Hence, 8 is an even number.
Comments
Post a Comment
Leave Comment