Kotlin Program to Check Whether a Number is Positive or Negative

Logic to solve this problem:

  • If the number is greater than zero, it is a positive number.
  • If the number is less than zero, it is a negative number.
  • If both conditions are not satisfied, the number is zero.

Example 1: Using if...else statement

fun main(args: Array<String>) {

    val number = 12.3

    if (number < 0.0)
        println("$number is a negative number.")
    else if (number > 0.0)
        println("$number is a positive number.")
    else
        println("$number is 0.")
}

When you run the program, the output will be:

12.3 is a positive number.

Here's the equivalent Java code: Java Program to Check if a Number is Positive or Negative.


We can also use a when expression instead of an if...else expression to solve this problem.

Example 2: Using when expression

fun main(args: Array<String>) {

    val number = -12.3

    when {
        number < 0.0 -> println("$number is a negative number.")
        number > 0.0 -> println("$number is a positive number.")
        else -> println("$number is 0.")
    }
}

When you run the program, the output will be:

-12.3 is a negative number.
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community