Skip to main content

How to check if a number is positive, negative, or zero in Kotlin

How to check if a number is positive, negative, or zero in Kotlin.

Here is a step-by-step tutorial on how to check if a number is positive, negative, or zero in Kotlin:

Step 1: Declare a variable to hold the number you want to check. For example, let's assume you have a variable named "number" of type Int.

Step 2: Use an if-else statement to check if the number is positive, negative, or zero. Within the if-else statement, use the comparison operators to evaluate the number.

if (number > 0) {
// The number is positive
} else if (number < 0) {
// The number is negative
} else {
// The number is zero
}

Step 3: You can add specific actions or logic within each block of the if-else statement to perform different operations based on the result.

For example, if you want to print a message indicating the type of number, you can use the println() function:

if (number > 0) {
println("The number is positive")
} else if (number < 0) {
println("The number is negative")
} else {
println("The number is zero")
}

Step 4: Run the code and observe the output. The appropriate message will be printed based on the value of the number.

Here's a complete example:

fun main() {
val number: Int = -5

if (number > 0) {
println("The number is positive")
} else if (number < 0) {
println("The number is negative")
} else {
println("The number is zero")
}
}

This example will output "The number is negative" since the value of "number" is -5.

You can modify the value of the "number" variable to test different scenarios and observe the output accordingly.

That's it! You have successfully checked if a number is positive, negative, or zero in Kotlin.