Question

The attributes of three arithmetic operators in some programming language are given below.

OperatorPrecedenceAssociativityArity
+HighLeftBinary
-MediumRightBinary
*LowLeftBinary

The value of the expression 2−5+1−7∗32 - 5 + 1 - 7 * 3 in this language is _____.

Official answer and solution
Official answer
9
From
Official GATE 2016 answer key

Solution

Evaluate the arithmetic expression following the given precedence and associativity rules step-by-step.

The attributes of the operators are:

  • +: High precedence, Left-associative
  • -: Medium precedence, Right-associative
  • *: Low precedence, Left-associative

Expression to evaluate: 2−5+1−7∗32 - 5 + 1 - 7 * 3

Step 1: Evaluate the highest precedence operator +.

  • The sub-expression is 5+1=65 + 1 = 6.
  • Substituting this gives: 2−6−7∗32 - 6 - 7 * 3.

Step 2: Evaluate the medium precedence operator -.

  • The operator - is RIGHT-associative. Therefore, 2−6−72 - 6 - 7 must be parenthesized from the right: 2−(6−7)2 - (6 - 7).
  • Evaluating inner subtraction: 6−7=−16 - 7 = -1.
  • Evaluating outer subtraction: 2−(−1)=2+1=32 - (-1) = 2 + 1 = 3.
  • Substituting this back into the expression yields: 3∗33 * 3.

Step 3: Evaluate the lowest precedence operator *.

  • 3∗3=93 * 3 = 9.
Final answer

9

Common trap

Treating - as left-associative, which would calculate (2−6)−7=−4−7=−11(2 - 6) - 7 = -4 - 7 = -11, resulting in −11∗3=−33-11 * 3 = -33.

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

Source

Paper
GATE 2016 Computer Science and Information Technology (CS) Session 1
Question
55 of 65, printed as CS Q.45
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.