Kotlin program to check whether given number is positive, negative or zero

Kotlin | Checking number is positive, negative, or zero: Here, we are going to learn how to check whether a given number is positive, negative, or zero in Kotlin programming language? Submitted by IncludeHelp, on April 24, 2020

A positive number is a number which is greater than 0, a negative number is a number which is less than 0, else the number is Zero.

Problem statement

Given a number num, we have to check whether it is positive, negative, or zero.

Example:

Input:
num = 12321

Output:
12321 is positive

Program to check number is positive, negative or zero in Kotlin

/*
Kotlin Program to Check a Integer Number is Positive or Negative or Zero
if       number > 0 = Positive Number
else if  number < 0 = Negative Number
else     Number is 0 (Zero)
*/

package com.includehelp.basic

import java.util.*

//Main Function, Entry Point of Program
fun main(args: Array<String>) {
    // InputStream to get Input
    val reader = Scanner(System.`in`)
    
    //Input Integer number
    print("Enter Integer Number : ")
    val num = reader.nextInt()
    
    // using if else 
    println("Using if else...")
    if (num > 0)
        println("$num is a Positive Number")
    else if (num < 0)
        println("$num is a Negative Number")
    else
        println("Entered Number is Zero")
    
    // using when statement (similar to switch case)
    println("Using when statement...")        
    when{
        num> 0 -> println("$num is a Positive Number")
        num< 0 -> println("$num is a Negative Number")
        else  -> println("Entered Number is Zero")
    }
}

Output

Run 1:
Enter Integer Number : -10
Using if else...
-10 is a Negative Number
Using when statement...
-10 is a Negative Number

----

Run 2:
Enter Integer Number : 10
Using if else...
10 is a Positive Number
Using when statement...
10 is a Positive Number

----
Run 2:
Enter Integer Number : 0
Using if else...
Entered Number is Zero
Using when statement...
Entered Number is Zero

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.