Menu
Coddy logo textTech

Recap - Simple Calculator

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 34 of 93.

challenge icon

Challenge

Easy

Write a function calculate that takes a, b, and operation and returns the result of performing the specified operation on the two numbers.

Use if-else if-else chains to determine which arithmetic operation to perform based on the operation string.

Conditions:

  • If operation is "add", return the sum of a and b
  • If operation is "subtract", return a minus b
  • If operation is "multiply", return the product of a and b
  • If operation is "divide", return a divided by b (integer division)
  • For any other operation, return 0

Parameters:

  • a (Int): The first number
  • b (Int): The second number
  • operation (String): The operation to perform

Returns: The result of the calculation, or 0 if the operation is not recognized (Int)

Input constraints: For division, the second number is nonzero. All inputs and intermediate results fit in the declared numeric type.

Try it yourself

fun calculate(a: Int, b: Int, operation: String): Int {
    // Write code here
}

All lessons in Fundamentals

Practice on your own: Kotlin playground