Skip to content
DeveloperMemos

Checking Even or Odd Numbers with Kotlin

Kotlin, Even Numbers, Odd Numbers, Modulo Operator, Conditional Statements1 min read

In Kotlin, determining whether a number is even or odd is a fundamental task. Even numbers are integers that can be divided by 2 with no remainder, while odd numbers leave a remainder of 1 when divided by 2. This article explores two common approaches to achieving this in Kotlin:

1. Using the Modulo Operator (%) with an if Statement

The modulo operator (%) calculates the remainder after a division operation. Here's how you can use it to check for even or odd numbers:

1fun main() {
2 val number = 10
3
4 if (number % 2 == 0) {
5 println("$number is even")
6 } else {
7 println("$number is odd")
8 }
9}

In this code:

  1. We declare a variable number and assign a value to it.
  2. The if statement checks if the remainder of dividing number by 2 is equal to 0.
    • If the condition is true (number % 2 == 0), it means number is even, and the message inside the if block is printed.
    • Otherwise, the else block executes, indicating that number is odd.

2. Using an if Expression (Kotlin-Specific)

Kotlin allows if statements to be expressions, meaning they can return a value. This can be used for a more concise even/odd check:

1fun main() {
2 val number = 15
3 val evenOdd = if (number % 2 == 0) "even" else "odd"
4 println("$number is $evenOdd")
5}

Here, the if expression directly assigns the string "even" or "odd" to the evenOdd variable based on the condition.

Choosing the Right Approach

  • If you need a simple check within a larger block of code, the if statement approach with separate blocks might be more readable.
  • If you want a more compact solution for assigning the even/odd status to a variable, the if expression is preferable.

Both methods effectively determine even or odd numbers in Kotlin. Select the one that best suits your code's style and purpose.