0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Check Even or Odd Number

In Kotlin, you can check if a number is even or odd using if (number % 2 == 0) to test evenness and print the result accordingly.
📋

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, you divide it by 2 and look at the remainder. If the remainder is 0, the number is even; otherwise, it is odd. This is like splitting candies into pairs and seeing if any candy is left alone.
📐

Algorithm

1
Get the input number
2
Calculate the remainder when the number is divided by 2
3
If the remainder is 0, the number is even
4
Otherwise, the number is odd
5
Print the result
💻

Code

kotlin
fun main() {
    val number = 7
    if (number % 2 == 0) {
        println("$number is even")
    } else {
        println("$number is odd")
    }
}
Output
7 is odd
🔍

Dry Run

Let's trace the number 7 through the code to see how it checks even or odd.

1

Input number

number = 7

2

Calculate remainder

7 % 2 = 1

3

Check remainder

Since remainder is 1 (not 0), number is odd

4

Print result

Output: "7 is odd"

StepOperationValue
1Input number7
27 % 21
3Check if remainder == 0False
4Print output"7 is odd"
💡

Why This Works

Step 1: Using modulus operator

The % operator gives the remainder of division, which helps us find if a number divides evenly by 2.

Step 2: Even number check

If the remainder is 0, it means the number is divisible by 2 and is even.

Step 3: Odd number check

If the remainder is not 0, the number is not divisible by 2 and is odd.

🔄

Alternative Approaches

Using when expression
kotlin
fun main() {
    val number = 10
    when (number % 2) {
        0 -> println("$number is even")
        else -> println("$number is odd")
    }
}
This uses Kotlin's <code>when</code> expression for cleaner branching but works the same way.
Using a function to return boolean
kotlin
fun isEven(num: Int): Boolean = num % 2 == 0

fun main() {
    val number = 3
    if (isEven(number)) println("$number is even") else println("$number is odd")
}
This separates logic into a function, making code reusable and clearer.

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

Time Complexity

The operation uses a single modulus calculation and a simple condition, so it runs in constant time.

Space Complexity

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

Which Approach is Fastest?

All approaches use the modulus operator once, so they have the same speed; differences are mainly in code style.

ApproachTimeSpaceBest For
If-else with modulusO(1)O(1)Simple and clear checks
When expressionO(1)O(1)Cleaner branching syntax
Function returning booleanO(1)O(1)Reusable logic in larger programs
💡
Use number % 2 == 0 to quickly check if a number is even in Kotlin.
⚠️
Beginners often forget to use the modulus operator and try to check evenness by dividing, which doesn't work correctly.