CodeBlanks Logo Icon CodeBlanks

Multiply and divide

Add multiplication, division and the divide-by-zero check.

multiply and divide

Let's add multiplication and division to the calculator. multiply computes a * b. divide computes a / b; but when b == 0 it returns 0 — because integer division by zero throws ArithmeticException in Kotlin.

fun multiply(a: Int, b: Int): Int {
    return a * b
}

fun divide(a: Int, b: Int): Int {
    if (b == 0) {
        return 0
    }
    return a / b
}

Practice Add multiply and divide

Add fun multiply(a: Int, b: Int): Int { return a * b } and fun divide(a: Int, b: Int): Int { if (b == 0) { return 0 }; return a / b } to the existing code. Inside main, add println(multiply(5, 3)) and println(divide(10, 2)); keep existing calls.

Starter code

Main.kt
fun add(a: Int, b: Int): Int {
    return a + b
}
fun subtract(a: Int, b: Int): Int {
    return a - b
}
fun main() {
    println("Calculator")
    println(add(5, 3))
    println(subtract(5, 3))
}

Sample solution

Main.kt
fun add(a: Int, b: Int): Int {
    return a + b
}
fun subtract(a: Int, b: Int): Int {
    return a - b
}
fun multiply(a: Int, b: Int): Int {
    return a * b
}
fun divide(a: Int, b: Int): Int {
    if (b == 0) {
        return 0
    }
    return a / b
}
fun main() {
    println("Calculator")
    println(add(5, 3))
    println(subtract(5, 3))
    println(multiply(5, 3))
    println(divide(10, 2))
}

Expected output

Calculator
8
2
15
5

Division by zero

Integer division by zero (a / 0) throws ArithmeticException at runtime in Kotlin. So the divide function checks with if (b == 0) and safely returns 0.

Such preventive checks are especially important when working with user input. A user can enter zero; the program must not crash.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 multiply return

Question
fun multiply(a: Int, b: Int): Int {
    return a ____ b
}
Answer
fun multiply(a: Int, b: Int): Int {
    return a * b
}

Explanation: multiply performs multiplication.

2 Match the operations

Term Meaning
add +
subtract -
multiply *
divide /

3 What does `divide(10, 0)` return with this divide function?

  • 0 Correct answer
  • 10
  • It throws an error
  • 1

Explanation: The divide function checks for zero and returns 0.

All lessons in Beginner