Skip to Content
Learn
Using Number Variables
Arithmetic Operators

The arithmetic operators that exist in Kotlin resemble the operators we know from basic math. They can be used in various applications from calculating the average test grade for a student class to determining the total restaurant bill.

Kotlin supports the following arithmetic operators:

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % modulus (divides and gives the remainder)

The above arithmetic operators aside from modulus, %, should all be familiar. Modulus is a programming symbol that is used to calculate the division and return the remainder. For example:

println(7 % 2)

7 gets divided by 2 and results in 3 remainder 1. The remainder then gets returned and printed to the terminal:

1

Within the println() statement above, we built an arithmetic expression. An arithmetic expression is the grouping of arithmetic operators and numeric values. Take a look at some of the ways in which we can set up and use arithmetic expressions throughout a Kotlin program.

With variables:

var operand1 = 5.5 var operand2 = 4.3 println(operand1 + operand2) // Prints: 9.8

In a print statement:

println(8 - 4) // Prints: 4

Concatenated within a String:

println("The quotient of -9 and 3 is " + -9 / 3) // Prints: The quotient of -9 and 3 is -3

In the { } of a String template:

println("The product of 6 and 2, is ${6 * 2}") // Prints: The product of 6 and 2 is 12

Instructions

1.

In Arithmetic.kt, we’re going to use our knowledge of arithmetic operators to calculate the total restaurant bill. Let’s get started!

Observe the variables containing the price of each ordered meal. Declare two more variables:

  • total containing an arithmetic expression that adds each meal price:

    meal1 + meal2 + meal3
  • tip holding the value, 0.15.

2.

Declare the final variable, finalAmount, which we’ll use to calculate the total amount including the tip. Initialize finalAmount with the following arithmetic expression:

total * tip + total

Finally, use a println() statement to output finalAmount and see the total bill.

Folder Icon

Take this course for free

Already have an account?