How to check if a number is even or odd in Kotlin
How to check if a number is even or odd in Kotlin.
Here's a detailed step-by-step tutorial on how to check if a number is even or odd in Kotlin.
Step 1: Define the number to be checked
First, you need to define the number that you want to check if it is even or odd. For example, let's say we want to check if the number 7 is even or odd.
Step 2: Use the modulo operator (%)
The modulo operator (%) in Kotlin returns the remainder when one number is divided by another. By using the modulo operator, we can check if the remainder of dividing the number by 2 is zero or not.
Step 3: Check if the remainder is zero
To check if a number is even or odd, we need to check if the remainder of dividing the number by 2 is zero or not. If the remainder is zero, then the number is even; otherwise, it is odd.
Step 4: Implement the code
Now that we have the steps, let's implement the code in Kotlin.
fun main() {
val number = 7
if (number % 2 == 0) {
println("$number is even")
} else {
println("$number is odd")
}
}
In this code, we define the number as 7. We then use the if-else statement to check if the remainder of dividing the number by 2 is zero or not. If the remainder is zero, it means the number is even, so we print "7 is even". Otherwise, if the remainder is not zero, it means the number is odd, so we print "7 is odd".
Step 5: Test the code
To test the code, you can run it and see the output. In this case, when you run the code, you will see the output "7 is odd" because 7 is an odd number.
Additional Examples:
- Checking if a number is even:
fun isEven(number: Int): Boolean {
return number % 2 == 0
}
In this example, we define a function isEven that takes an integer parameter number and returns a boolean value. The function checks if the remainder of dividing the number by 2 is zero. If it is zero, it returns true, indicating that the number is even. Otherwise, it returns false, indicating that the number is odd.
- Using when expression:
fun main() {
val number = 10
val result = when (number % 2) {
0 -> "even"
else -> "odd"
}
println("$number is $result")
}
In this example, we use the when expression to check if the remainder of dividing the number by 2 is zero or not. If the remainder is zero, it assigns the string "even" to the result variable. Otherwise, it assigns the string "odd" to the result variable. Finally, we print the result along with the number.
That's it! You now know how to check if a number is even or odd in Kotlin.