Scala program to check whether a given number is EVEN or ODD using ternary operator

Here, we are going to learn how to check whether a given number is EVEN or ODD using ternary operator in Scala programming language?
Submitted by Nidhi, on April 26, 2021 [Last updated : March 09, 2023]

Scala – Check EVEN/ODD Number using Ternary Operator

Here, we will read the value of an integer variable from the user and check the entered number is EVEN or ODD using the ternary operator, and print the result on the console screen.

Scala code to check whether a given number is EVEN or ODD using ternary operator

The source code to check whether a given number is EVEN or ODD using the ternary operator is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to find the number is 
// EVEN or ODD using ternary operator

object Sample{  
    def main(args:Array[String]){  
        var num:Int=0
        var result:String=""
        
        print("Enter number: ")
        num = scala.io.StdIn.readInt()
        
        result = if (num%2==0) "EVEN" else "ODD"
        
        println("Number is: "+result)
    }  
}

Output

Enter number: 13
Number is: ODD

Explanation

In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.

In the main() function, we created an integer variable num with initial value 0. Here, we also created a string variable result. Then we read the value of the integer variable num from the user. After that, we checked the entered number is EVEN or ODD using the ternary operator and assigned the string into the result variable, and printed the appropriate message on the console screen.

Note: In the Scala ternary operator using the if-else construct, Scala does not support the traditional ternary operator.

Scala Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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