Kotlin Program: Check a number positive, negative, or zero
Write a Kotlin program to check if a given number is positive, negative, or zero.
Pre-Knowledge (Before you start!)
- Basic Kotlin Syntax.
- Kotlin Functions.
- Variables in Kotlin.
- Conditional Statements.
- Comparison Operators.
- String Interpolation.
- Printing Output.
Hints (Try before looking at the solution!)
- Define the main() Function.
- Declare a Number Variable.
- Display the Number.
- Use Conditional Statements.
- Test with Different Numbers.
- Common Errors to Avoid:
- Forgetting to handle zero.
- Misplacing logic in if-else statements.
- Using assignment instead of comparison.
Sample Solution:
Kotlin Code:
fun main()
{
val number = 1
//val number = -4
//val number = 0
println("Number is: $number")
if (number > 0)
{
println("The number is positive.")
}
else if (number < 0)
{
println("The number is negative.")
}
else
{
println("The number is zero.")
}
}
Sample Output:
Input a number: Number is: 1.0 The number is positive.
Number is: -4 The number is negative.
Number is: 0 The number is zero.
Explanation:
In the above exercise,
- If the number is greater than 0, it is considered positive, and the corresponding message is printed.
- If the number is less than 0, it is considered negative, and the corresponding message is printed.
- If the number is neither greater nor less than 0, it must be 0, and the corresponding message is printed.
Kotlin Editor:
Previous: Kotlin Control Flow Exercises Home.
Next: Check number divisibility by 7.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics