Learn
Using Number Variables
Order of Operations

As seen in the previous exercise, Kotlin allows us to combine or chain arithmetic expressions in order to achieve more complex calculations. When doing so, we must keep in mind the order in which each expression gets evaluated.

Most programming languages follow a certain order of operations (similar to PEMDAS) when evaluating such expressions. In Kotlin, this order looks like:

  1. Parentheses
  2. Multiplication
  3. Division
  4. Modulus
  5. Addition
  6. Subtraction

You may have noticed that we skipped over the E (Exponents) in PEMDAS. This is because Kotlin does not have an exponent operator and instead relies on the .pow() function to calculate exponentiation. We’ll cover this more in-depth in the following exercise.

Let’s see a few examples of compound arithmetic expressions:

println(5 + 8 * 2 / 4 - 3) // Prints: 6 println(3 + (5 + 5) / 2) // Prints: 8 println(3 * 2 + 1 * 7) // Prints: 13

Another rule to keep in mind is when an expression contains sister operations such as multiplication and division or addition and subtraction, side by side. The compiler will evaluate this expression in a left to right order. For example:

println(3 + 16 / 2 * 4) // Prints: 35

Since we have division, /, and multiplication, *, side by side, the left to right order goes into effect and the expression evaluates as such:

Diagram showing flow of operations of arithmetic expressions without parentheses

Keep in mind both sets of rules when creating complex arithmetic expressions.

Instructions

1.

In Operations.kt, we’ve set up multiple arithmetic expressions that are missing arithmetic operators.

Add an arithmetic operator in place of ___ to complete each expression.

  • answer1 should be 14
  • answer2 should be 3
  • answer3 should be 11

Note: You will see an error in the terminal on the right if there are still any ___ present in your code. The error should go away after you’ve replaced each ___ with the correct operator.

Folder Icon

Take this course for free

Already have an account?