English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to check if a number is even or odd

Kotlin Examples Comprehensive Collection

In this program, you will learn to check if the number entered by the user is even or odd. This will be done using two variants of if ... else in Kotlin.

Example1:Check if a number is even or odd using if ... else statement

import java.util.*
fun main(args: Array<String>) {
    val reader = Scanner(System.`in`)
    print("Enter a number:")
    val num = reader.nextInt()
    if (num % 2 == 0)
        println("$num is even")
    else
        println("$num is odd")
}

When running the program, the output is:

Enter a number: 12
12 is even

In the above program, a Scanner object named reader is created to read a number from the user's keyboard. The entered number is then stored in the variable num.

Now, to check if num is even or odd, we use the % operator to calculate the remainder and check if it is divisible by2divisible.

For this, we use if ... else statements in Java. If num is divisible by2If divisible, print num is even. Otherwise, we print num is odd.

We can also use if ... else as an expression to check if num is even or odd.

Example2:Check if a number is even or odd using if ... else expression

import java.util.*
fun main(args: Array<String>) {
    val reader = Scanner(System.`in`)
    print("Enter a number:")
    val num = reader.nextInt()
    val evenOdd = if (num % 2 == 0) "even" else "odd"
    println("$num is $evenOdd")
}

When running the program, the output is:

Enter a number: 13
13 is an odd number

Unlike Java, if ... else statements are also expressions in Kotlin. Therefore, you can store the return value of if ... else statements in a variable. This is what Kotlin replaces the Java ternary operator (? :) with.

This is the equivalent code in Java: Check if a number is even or odd in Javais an even number or an odd number

In the above program, if the num is2If the division is exact, it returns an even number. Otherwise, it returns an odd number. The returned value is stored in the string variable evenOdd.

Then, use println() to print the result on the screen.

Kotlin Examples Comprehensive Collection