Kotlin – Basic Calculator
In Kotlin, you can create a simple calculator program that performs basic arithmetic operations such as addition, subtraction, multiplication, and division. This tutorial will guide you through the process of writing a Kotlin program for a basic calculator.
Step 1: Define the Calculator Functions
Create functions for each arithmetic operation: addition, subtraction, multiplication, and division.
fun add(a: Double, b: Double): Double {
return a + b
}
fun subtract(a: Double, b: Double): Double {
return a - b
}
fun multiply(a: Double, b: Double): Double {
return a * b
}
fun divide(a: Double, b: Double): Double {
if (b == 0.0) {
throw IllegalArgumentException("Cannot divide by zero")
}
return a / b
}
Step 2: Create the Calculator Function
Create a function that takes input for the operation type (addition, subtraction, multiplication, division) and two numbers, and then calls the corresponding calculator function.
fun calculate(operation: Char, a: Double, b: Double): Double {
return when (operation) {
'+' -> add(a, b)
'-' -> subtract(a, b)
'*' -> multiply(a, b)
'/' -> divide(a, b)
else -> throw IllegalArgumentException("Invalid operation")
}
}
Step 3: Use the Calculator Function
Call the calculate
function with the operation type (+, -, *, /) and two numbers, and print the result.
fun main() {
val operation = '+'
val num1 = 10.0
val num2 = 5.0
val result = calculate(operation, num1, num2)
println("Result of $num1 $operation $num2 = $result")
}
Complete Kotlin Program
The following is the complete Kotlin program for a basic calculator.
Kotlin Program
fun add(a: Double, b: Double): Double {
return a + b
}
fun subtract(a: Double, b: Double): Double {
return a - b
}
fun multiply(a: Double, b: Double): Double {
return a * b
}
fun divide(a: Double, b: Double): Double {
if (b == 0.0) {
throw IllegalArgumentException("Cannot divide by zero")
}
return a / b
}
fun calculate(operation: Char, a: Double, b: Double): Double {
return when (operation) {
'+' -> add(a, b)
'-' -> subtract(a, b)
'*' -> multiply(a, b)
'/' -> divide(a, b)
else -> throw IllegalArgumentException("Invalid operation")
}
}
fun main() {
val operation = '+'
val num1 = 10.0
val num2 = 5.0
val result = calculate(operation, num1, num2)
println("Result of $num1 $operation $num2 = $result")
}
Output
Result of 10.0 + 5.0 = 15.0
Summary
By following these steps and using functions for arithmetic operations, you can create a basic calculator program in Kotlin.