— Kotlin, Even Numbers, Odd Numbers, Modulo Operator, Conditional Statements — 1 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:
%) with an if StatementThe 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 = 103
4 if (number % 2 == 0) {5 println("$number is even")6 } else {7 println("$number is odd")8 }9}In this code:
number and assign a value to it.if statement checks if the remainder of dividing number by 2 is equal to 0.number % 2 == 0), it means number is even, and the message inside the if block is printed.else block executes, indicating that number is odd.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 = 153 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.
if statement approach with separate blocks might be more readable.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.