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 / /

  1. Evaluate left to right using the RPN:

  2. 3 1 + → 4

  3. 4 5 + → 9

  4. 9 2 * → 18

  5. 7 2 + → 9

  6. Evaluate the chained subtractions: 7 6 - = 1; then 4 - 1 = 3; then 9 - 3 = 6

  7. 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.

Explore the full course: Gate Guidance By Sanchit Sir