CodeBlanks Logo Icon CodeBlanks

Add and subtract

Add and test the addition and subtraction functions.

The add and subtract functions

The first two functions of the calculator are add and subtract. Both take two Ints and return an Int. add computes a + b; subtract computes a - b.

fun add(a: Int, b: Int): Int {
    return a + b
}

fun subtract(a: Int, b: Int): Int {
    return a - b
}

You can call these from main as add(5, 3) and subtract(5, 3).

Practice Add add and subtract

Above the existing main, add fun add(a: Int, b: Int): Int { return a + b } and fun subtract(a: Int, b: Int): Int { return a - b }. Inside main, add println(add(5, 3)) and println(subtract(5, 3)); keep the existing println.

Starter code

Main.kt
fun main() {
    println("Calculator")
}

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 main() {
    println("Calculator")
    println(add(5, 3))
    println(subtract(5, 3))
}

Expected output

Calculator
8
2

When to use a function?

If you'll perform the same calculation in several places, it's good to move it into a function. In the calculator, add(5, 3) and add(10, 20) share code; this reduces errors and improves readability.

Functions also make testing easier by breaking code into pieces. Putting each operation in its own function simplifies debugging in the calculator.

Questions and answers

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

1 Match the concepts

Term Meaning
fun Function
Int Integer
return Return
println Output

2 What does `add(5, 3)` return?

  • It throws an error
  • 2
  • 15
  • 8 Correct answer

Explanation: The add function sums two numbers.

3 Complete the return statement

Question
fun subtract(a: Int, b: Int): Int {
    return a ____ b
}
Answer
fun subtract(a: Int, b: Int): Int {
    return a - b
}

Explanation: subtract performs subtraction.

All lessons in Beginner