Consider the operator precedence and associativity rules for the integer…
2024
Consider the operator precedence and associativity rules for the integer arithmetic operators given in the table below.
Operator | Precedence Level | Associativity |
|---|---|---|
+ | Highest | Left |
− | High | Right |
* | Medium | Right |
/ | Low | Right |
The value of the expression 3 + 1 + 5 ∗ 2 / 7 + 2 − 4 − 7 − 6 / 2 as per the above rules is __________
Attempted by 374 students.
Show answer & explanation
Correct answer: 6
Key idea: apply the given custom precedence and associativity rules to determine evaluation order. Here the precedence (highest to lowest) is: + (left-associative), - (right-associative), * (right-associative), / (right-associative).
Convert the expression to Reverse Polish Notation (RPN) using these precedences and associativities, then evaluate the RPN.
The RPN form is: 3 1 + 5 + 2 * 7 2 + 4 7 6 - - - 2 / /
Evaluate left to right using the RPN:
3 1 + → 4
4 5 + → 9
9 2 * → 18
7 2 + → 9
Evaluate the chained subtractions: 7 6 - = 1; then 4 - 1 = 3; then 9 - 3 = 6
Divide: 6 / 2 = 3, then 18 / 3 = 6
Final result: 6
A video solution is available for this question — log in and enroll to watch it.