Solution Review: Arithmetic Operators

In this review: we give a detailed analysis of the solution to this exercise.

Solution #1: Operator Precedence

Press + to interact
ans <- 4 * 9
ans <- ans + 2
ans <- ans - 8
cat(ans)

Explanation

The given task here was to find the value of the equation

2 + 4 * 9 - 8

Mathematically, we need to find the value of the multiplying numbers first, keeping in mind operator precedence. So, we multiply 44 and 99 and save the value in the variable ans. Next, we perform addition. We can either perform subtraction or addition first, but we move from left to right: add 22 to ans and store in ans, then, subtract 88 from ans.

Operator precedence determines which operator is performed first in an expression with more than one operators.

  • *, / and % operators have equal precedence.
  • + and - operators have equal precedence.
  • *, / and % have higher precedence than + and -. The operator with higher precedence is executed first in the expression.

Solution #2: Using the Entire Expression Directly

Press + to interact
cat(2 + 4 * 9 - 8)

Explanation

This is the simpler method, just find the value of the entire string and pass to cat() for printing. Here, operator precedence will be handled by R compiler itself.