A simple calculator is a basic yet useful application that performs arithmetic operations like addition, subtraction, multiplication, and division. Kotlin’s switch…case construct allows us to create a simple calculator with ease. In this article, we’ll explore three different Kotlin Program to Make a Simple Calculator Using switch…case.
1. Addition Calculator
This example demonstrates how to create an addition calculator using switch…case in Kotlin. The user inputs two numbers, and the program adds them together.
Code
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
println("Enter first number:")
val num1 = scanner.nextDouble()
println("Enter second number:")
val num2 = scanner.nextDouble()
val result = num1 + num2
println("Sum: $result")
}
1.3 Output (Sample Input: 5 and 3)
Enter first number:
5
Enter second number:
3
Sum: 8.0
2. Subtraction Calculator
In this example, we create a subtraction calculator using switch…case in Kotlin. The user inputs two numbers, and the program subtracts the second number from the first.
Code
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
println("Enter first number:")
val num1 = scanner.nextDouble()
println("Enter second number:")
val num2 = scanner.nextDouble()
val result = num1 - num2
println("Difference: $result")
}
2.3 Output (Sample Input: 10 and 4)
Enter first number:
10
Enter second number:
4
Difference: 6.0
3. Multiplication Calculator
Here, we create a multiplication calculator using switch…case in Kotlin. The user inputs two numbers, and the program multiplies them together.
Code
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
println("Enter first number:")
val num1 = scanner.nextDouble()
println("Enter second number:")
val num2 = scanner.nextDouble()
val result = num1 * num2
println("Product: $result")
}
Output
Enter first number:
6
Enter second number:
7
Product: 42.0
4. Conclusion
Creating a simple calculator using switch…case in Kotlin is straightforward and efficient. Each example showcased here demonstrates how to perform different arithmetic operations such as addition, subtraction, and multiplication. You can expand upon these examples to include division or additional operations based on your requirements. Understanding switch…case constructs in Kotlin empowers you to build versatile and user-friendly calculator applications, enhancing your Kotlin programming skills in the process.