Odd Number Program in Kotlin
In Kotlin, you can check if given number is an odd number or not, by dividing the given number with 2, and checking if the remainder is one or not.
To find the remainder, we can use Arithmetic Modulus Operator, and to check if the remainder is one, we can use Equal-to Operator.
For example, if n
is the given number, then the boolean expression to check if n
is an odd number is
n % 2 == 1
We can use this as a condition in if-else statement.
Examples
Check if 21 is odd number
In the following example, we take a number in n
, say 21, and check if this is an odd number or not.
Kotlin Program
fun main() {
val n = 21
if (n % 2 == 1) {
println("$n is odd.")
} else {
println("$n is not odd.")
}
}
Output
21 is odd.
Check if 26 is odd number
In the following example, we take a number in n
, say 26, and check if this is an odd number or not.
Kotlin Program
fun main() {
val n = 26
if (n % 2 == 1) {
println("$n is odd.")
} else {
println("$n is not odd.")
}
}
Output
26 is not odd.