0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Create Simple Calculator

A simple Kotlin calculator program reads two numbers and an operator, then uses when to perform addition, subtraction, multiplication, or division, like when(operator) { "+" -> num1 + num2; "-" -> num1 - num2; "*" -> num1 * num2; "/" -> num1 / num2 }.
📋

Examples

Inputnum1=5, num2=3, operator='+'
OutputResult: 8.0
Inputnum1=10, num2=2, operator='/'
OutputResult: 5.0
Inputnum1=7, num2=0, operator='/'
OutputCannot divide by zero
🧠

How to Think About It

To build a simple calculator, first get two numbers and an operator from the user. Then check which operator was entered using when. Perform the matching math operation. Handle division carefully to avoid dividing by zero. Finally, show the result.
📐

Algorithm

1
Get the first number from the user
2
Get the second number from the user
3
Get the operator (+, -, *, /) from the user
4
Use a decision structure to check the operator
5
Perform the corresponding operation
6
If division, check if second number is zero to avoid error
7
Print the result or error message
💻

Code

kotlin
fun main() {
    print("Enter first number: ")
    val num1 = readLine()!!.toDouble()
    print("Enter second number: ")
    val num2 = readLine()!!.toDouble()
    print("Enter operator (+, -, *, /): ")
    val operator = readLine()!!

    val result = when (operator) {
        "+" -> num1 + num2
        "-" -> num1 - num2
        "*" -> num1 * num2
        "/" -> if (num2 != 0.0) num1 / num2 else null
        else -> null
    }

    if (result != null) {
        println("Result: $result")
    } else {
        println("Cannot divide by zero or invalid operator")
    }
}
Output
Enter first number: 5 Enter second number: 3 Enter operator (+, -, *, /): + Result: 8.0
🔍

Dry Run

Let's trace the input num1=5, num2=3, operator='+' through the code

1

Read first number

num1 = 5.0

2

Read second number

num2 = 3.0

3

Read operator

operator = '+'

4

Check operator and calculate

operator is '+', so result = 5.0 + 3.0 = 8.0

5

Print result

Output: Result: 8.0

StepVariableValue
1num15.0
2num23.0
3operator+
4result8.0
💡

Why This Works

Step 1: Reading inputs

The program uses readLine() to get user input as strings and converts numbers to Double for calculations.

Step 2: Choosing operation

The when expression selects the math operation based on the operator entered.

Step 3: Handling division

Before dividing, the program checks if the divisor is zero to avoid errors and returns null if invalid.

Step 4: Displaying result

If the result is valid, it prints it; otherwise, it shows an error message.

🔄

Alternative Approaches

Using if-else instead of when
kotlin
fun main() {
    print("Enter first number: ")
    val num1 = readLine()!!.toDouble()
    print("Enter second number: ")
    val num2 = readLine()!!.toDouble()
    print("Enter operator (+, -, *, /): ")
    val operator = readLine()!!

    val result = if (operator == "+") {
        num1 + num2
    } else if (operator == "-") {
        num1 - num2
    } else if (operator == "*") {
        num1 * num2
    } else if (operator == "/") {
        if (num2 != 0.0) num1 / num2 else null
    } else null

    if (result != null) {
        println("Result: $result")
    } else {
        println("Cannot divide by zero or invalid operator")
    }
}
This uses if-else chains instead of when; it works but is less concise.
Using functions for each operation
kotlin
fun add(a: Double, b: Double) = a + b
fun subtract(a: Double, b: Double) = a - b
fun multiply(a: Double, b: Double) = a * b
fun divide(a: Double, b: Double) = if (b != 0.0) a / b else null

fun main() {
    print("Enter first number: ")
    val num1 = readLine()!!.toDouble()
    print("Enter second number: ")
    val num2 = readLine()!!.toDouble()
    print("Enter operator (+, -, *, /): ")
    val operator = readLine()!!

    val result = when (operator) {
        "+" -> add(num1, num2)
        "-" -> subtract(num1, num2)
        "*" -> multiply(num1, num2)
        "/" -> divide(num1, num2)
        else -> null
    }

    if (result != null) {
        println("Result: $result")
    } else {
        println("Cannot divide by zero or invalid operator")
    }
}
This separates operations into functions for clearer structure and easier extension.

Complexity: O(1) time, O(1) space

Time Complexity

The program performs a fixed number of operations regardless of input size, so it runs in constant time O(1).

Space Complexity

It uses a few variables to store inputs and results, so space usage is constant O(1).

Which Approach is Fastest?

All approaches run in constant time; using when is more concise and readable than if-else chains.

ApproachTimeSpaceBest For
Using whenO(1)O(1)Simple, readable code
Using if-elseO(1)O(1)Familiar to beginners but less concise
Using functionsO(1)O(1)Better structure for larger calculators
💡
Always check for division by zero to avoid runtime errors in your calculator.
⚠️
Beginners often forget to convert input strings to numbers before calculations.