Solution Review: Arithmetic Operators
In this review: we give a detailed analysis of the solution to this exercise.
We'll cover the following...
Solution #1: Operator Precedence
ans <- 4 * 9ans <- ans + 2ans <- ans - 8cat(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 and 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 to ans and store in ans, then, subtract 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
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.