0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Check Even or Odd Number

Use the modulo operator in PowerShell like $number % 2 -eq 0 to check if a number is even; if true, it's even, else odd.
📋

Examples

Input4
Output4 is even
Input7
Output7 is odd
Input0
Output0 is even
🧠

How to Think About It

To check if a number is even or odd, divide it by 2 and look at the remainder. If the remainder is zero, the number is even; otherwise, it is odd.
📐

Algorithm

1
Get the input number
2
Calculate the remainder when dividing the number by 2
3
If the remainder is 0, return 'even'
4
Otherwise, return 'odd'
💻

Code

powershell
param([int]$number)
if ($number % 2 -eq 0) {
    Write-Output "$number is even"
} else {
    Write-Output "$number is odd"
}
Output
4 is even
🔍

Dry Run

Let's trace the number 4 through the code

1

Input number

number = 4

2

Calculate remainder

4 % 2 = 0

3

Check remainder

0 equals 0, so number is even

NumberRemainderResult
40even
💡

Why This Works

Step 1: Modulo operator

The % operator gives the remainder of division, which helps identify even or odd numbers.

Step 2: Comparison

If the remainder is 0, the number divides evenly by 2, so it is even.

Step 3: Output

Based on the check, the script outputs whether the number is even or odd.

🔄

Alternative Approaches

Using if-else with -ne operator
powershell
param([int]$number)
if ($number % 2 -ne 0) {
    Write-Output "$number is odd"
} else {
    Write-Output "$number is even"
}
This flips the condition but achieves the same result; slightly different readability.
Using switch statement
powershell
param([int]$number)
switch ($number % 2) {
    0 { Write-Output "$number is even" }
    default { Write-Output "$number is odd" }
}
Uses switch for clarity when checking multiple cases, useful if extended.

Complexity: O(1) time, O(1) space

Time Complexity

The operation uses a single modulo calculation and comparison, which takes constant time.

Space Complexity

No extra memory is needed beyond the input and a few variables, so space is constant.

Which Approach is Fastest?

All approaches use a single modulo operation; differences are only in readability, not performance.

ApproachTimeSpaceBest For
Modulo with -eqO(1)O(1)Simple and clear even/odd check
Modulo with -neO(1)O(1)Alternative condition style
Switch statementO(1)O(1)Extensible for multiple cases
💡
Use $number % 2 -eq 0 to quickly check if a number is even in PowerShell.
⚠️
Beginners often forget to use the modulo operator and try to compare the number directly to 2.