Kotlin mod()
In Kotlin, the mod()
function is used to find the remainder of the division of two numbers.
In this tutorial, we’ll explore the syntax of the mod()
function and provide examples of its usage in Kotlin.
Syntax
The syntax of the mod()
function is:
fun Byte.mod(other: Byte): Byte
fun Byte.mod(other: Short): Short
fun Byte.mod(other: Int): Int
fun Byte.mod(other: Long): Long
fun Short.mod(other: Byte): Byte
fun Short.mod(other: Short): Short
fun Short.mod(other: Int): Int
fun Short.mod(other: Long): Long
fun Int.mod(other: Byte): Byte
fun Int.mod(other: Short): Short
fun Int.mod(other: Int): Int
fun Int.mod(other: Long): Long
fun Long.mod(other: Byte): Byte
fun Long.mod(other: Short): Short
fun Long.mod(other: Int): Int
fun Long.mod(other: Long): Long
fun Float.mod(other: Float): Float
fun Float.mod(other: Double): Double
fun Double.mod(other: Float): Double
fun Double.mod(other: Double): Double
The mod() function calculates the remainder of flooring division of this value (dividend) by the other value (divisor).
Examples for mod() function
1. Using mod() to find the remainder of the division 25/7
In this example, we’ll use mod()
to find the remainder in the division of 25 by 7.
Kotlin Program
fun main() {
val dividend = 25
val divisor = 7
val remainder = dividend.mod(divisor)
println("remainder in $dividend/$divisor is $remainder")
}
Output
remainder in 25/7 is 4
2. Using mod() to Check Even or Odd
In this example, we’ll use mod()
to determine if a number is even or odd.
Kotlin Program
fun main() {
val number = 7
// Using mod() to check if the number is even or odd
val isEven = number.mod(2) == 0
// Printing the result
if (isEven) {
println("$number is even.")
} else {
println("$number is odd.")
}
}
Output
7 is odd.
In this example, the mod()
operator is used to check if a given number is even or odd by dividing it by 2. The result is then printed to the console.
Summary
In this tutorial, we’ve covered the mod()
operator in Kotlin, its syntax, and how to use it for calculating the remainder of the division of one number by another.