Scala program to implement an arithmetic calculator using a match case

Here, we are going to learn how to implement an arithmetic calculator using a match case in Scala programming language?
Submitted by Nidhi, on April 28, 2021 [Last updated : March 10, 2023]

Scala – Arithmetic Calculator using Match Statement

Here, we will implement an arithmetic calculator using the match case. Here we will read two numbers and perform the selected operation.

Scala code to implement an arithmetic calculator using a match case

The source code to implement the arithmetic calculator using the match case is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement arithmetic calculator
// using "match" case

object Sample {
    def main(args: Array[String]) {  
        var ch:Char=0
        var num1:Int=0
        var num2:Int=0
        var result:Int=0
        print("Choose operation to perform (+,-,*,/,%): ")
        print("Enter first number: ")
        print("Enter second number: ")
        ch match{
            case '+'=> result=num1+num2 
            case '-'=> result=num1-num2
            case '*'=> result=num1*num2
            case '/'=> result=num1/num2
            case '%'=> result=num1%num2
            case _=>printf("Invalid operation.\n")
        println("Result: "+result);


Choose operation to perform (+,-,*,/,%): *
Enter first number: 10
Enter second number: 20
Result: 200


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 four variables ch, num1, num2, result. Here, we choose operation by entering character and then enter both integer numbers. After that, we performed a selected operation using the match case and print the result on the console screen.

Scala Pattern Matching Programs »


Top MCQs

Comments and Discussions!

© some rights reserved.