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

Problem Solution:

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.

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.

Scala Basic Programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.