w3resource

Kotlin Single-Expression Function: Check if the number is negative

Kotlin Function: Exercise-14 with Solution

Write a Kotlin single-expression function that takes a number as an argument and returns true if it is negative, false otherwise.

Sample Solution:

Kotlin Code:

fun isNegative(number: Int): Boolean = number < 0

fun main() {
    val num1 = -14
    val num2 = 20

    println("$num1 is negative: ${isNegative(num1)}")
    println("$num2 is negative: ${isNegative(num2)}")
}

Sample Output:

-14 is negative: true
20 is negative: false

Explanation:

In the above exercise -

The "isNegative()" function takes a parameter number of type Int and returns a boolean value. The function checks if the number is less than 0, and if so, it returns true, indicating that the number is negative. Otherwise, it returns false.

In the main function, we demonstrate the usage of the "isNegative()" function by passing two numbers, -14 and 20, as arguments. The function is called for each number, and the result is printed using println().

Kotlin Editor:


Previous: Print even numbers from list, Return Unit.
Next: Print asterisk pattern.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/kotlin-exercises/function/kotlin-function-exercise-14.php