Q:

Scala program to find the largest number between two numbers using ternary operator

belongs to collection: Scala Basic Programs

0

Here, we will read the value of two integer variables from the user and find the largest number using the ternary operator then print the largest number 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 find the largest number between two numbers 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 largest number between 
// two numbers using ternary operator

object Sample{  
    def main(args:Array[String]){  
        var num1:Int=0
        var num2:Int=0  
        var large:Int=0  
        
        print("Enter number1: ")
        num1 = scala.io.StdIn.readInt()
        
        print("Enter number2: ")
        num2 = scala.io.StdIn.readInt()
        
        large = if (num1 > num2) num1 else num2
        
        println("Largest number is: "+large)
    }  
}

Output:

Enter number1: 10
Enter number2: 20
Largest number is: 20

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 two integer variables num1 and num2. Then we read the value of variables from the user. After that, we found the largest number from them using the ternary operator and print the result 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 find the largest number among thr... >>
<< Scala program to read the value of character varia...