w3resource

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

Scala Control Flow Exercise-1 with Solution

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

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?



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://w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-1.php