w3resource

Scala Program: Check the number positive, negative, or zero


Write a Scala program to check if a given number is positive, negative, or zero using if/else statements.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, ensure you have a good understanding of the following concepts:

  • Conditional Statements: Understand how if, else if, and else statements work in Scala.
  • Comparison Operators: Learn how to compare numbers using >, <, and == to determine their value relative to zero.
  • Variable Declaration: Understand how to declare and assign values to variables in Scala.
  • Printing Output: Learn how to use println() to display results in the console.

Hints (Try Before Looking at the Solution!)

Consider the following hints to help you solve this exercise:

  • Hint 1: Use an if condition to check if the number is greater than zero.
  • Hint 2: Use an else if condition to check if the number is less than zero.
  • Hint 3: If the number is neither positive nor negative, it must be zero. Use an else statement to handle this case.
  • Hint 4: Try testing with different values, including positive, negative, and zero, to ensure your logic is correct.

Sample Solution:

Scala Code:

object NumberCheck {
  def main(args: Array[String]): Unit = {
      val n: Int = -7  
    //val n: Int = 5
    //val n: Int = 0

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

Sample Output:

The number -7 is negative.
The number 5 is positive.
The number is zero.

Explanation:

First we define a variable "n" and assign it a value to check. We use the if/else statements to check. If the number is greater than 0, we print "The number is positive." If the number is less than 0, we print "The number is negative." If the number is neither greater nor less than 0, it must be 0, and we print "The number is zero."

Scala Code Editor :

Previous: Scala Control Flow Exercises Home.
Next: Find the maximum of two numbers.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.