Q:

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

belongs to collection: Scala Basic Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to print the ASCII value of the corr... >>
<< Scala program to find the largest number among thr...