Question

Consider the operator precedence and associativity rules for the integer arithmetic operators given in the table below.

OperatorPrecedenceAssociativity
+HighestLeft
-HighRight
*MediumRight
/LowRight

The value of the expression 3+1+5∗2/7+2−4−7−6/23 + 1 + 5 * 2 / 7 + 2 - 4 - 7 - 6 / 2 as per the above rules is __________

Official answer and solution
Official answer
6
From
Official GATE 2024 answer key

Solution

Parenthesize and evaluate the expression strictly in decreasing order of custom precedence (+, then -, then *, then /).

Evaluating the expression 3+1+5∗2/7+2−4−7−6/23 + 1 + 5 * 2 / 7 + 2 - 4 - 7 - 6 / 2 step by step according to the given precedence table:

  1. + (Highest precedence, Left-associative):
    • ((3+1)+5)=9((3 + 1) + 5) = 9
    • (7+2)=9(7 + 2) = 9
      The expression reduces to: 9∗2/9−4−7−6/29 * 2 / 9 - 4 - 7 - 6 / 2
  2. - (High precedence, Right-associative):
    • (9−(4−(7−6)))=9−(4−1)=9−3=6(9 - (4 - (7 - 6))) = 9 - (4 - 1) = 9 - 3 = 6
      The expression reduces to: 9∗2/6/29 * 2 / 6 / 2
  3. * (Medium precedence, Right-associative):
    • (9∗2)=18(9 * 2) = 18
      The expression reduces to: 18/6/218 / 6 / 2
  4. / (Low precedence, Right-associative):
    • 18/(6/2)=18/3=618 / (6 / 2) = 18 / 3 = 6
Final answer

6

Common trap

Evaluating - or / left-to-right instead of right-to-left as specified in the table.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 1 (CS1)
Question
33 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.