GATE CS 2024 Set 1 — Question 33

NAT+1 / -0MediumExpression EvaluationStacks & QueuesProgramming & Data Structures

Programming & Data Structures → Stacks & Queues → Expression Evaluation

Last updated

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+52/7+2476/23 + 1 + 5 * 2 / 7 + 2 - 4 - 7 - 6 / 2 as per the above rules is __________

Correct answer

6 to 6

Solution

To evaluate the expression 3+1+52/7+2476/23 + 1 + 5 * 2 / 7 + 2 - 4 - 7 - 6 / 2, we follow the given precedence and associativity rules:
1.+ (Highest, Left-to-Right)
2. (High, Right-to-Left)
3. (Medium, Right-to-Left)
4./ (Low, Right-to-Left)
Step 1: Evaluate '+' (Highest precedence, Left associative)
There are three '+' operators. We evaluate them from left to right:
  • (3+1)=4(3 + 1) = 4
  • (4+5)=9(4 + 5) = 9
  • (7+2)=9(7 + 2) = 9

The expression becomes: 92/9476/29 * 2 / 9 - 4 - 7 - 6 / 2Step 2: Evaluate '−' (High precedence, Right associative)
The subtraction chain is 94769 - 4 - 7 - 6. Since it is right associative, we evaluate from right to left:
  • (76)=1(7 - 6) = 1
  • (41)=3(4 - 1) = 3
  • (93)=6(9 - 3) = 6

The expression becomes: 92/6/29 * 2 / 6 / 2Step 3: Evaluate '∗' (Medium precedence, Right associative)
There is one '*' operator:
  • (92)=18(9 * 2) = 18

The expression becomes: 18/6/218 / 6 / 2Step 4: Evaluate '/' (Low precedence, Right associative)
There are two '/' operators. Since it is right associative, we evaluate from right to left:
  • (6/2)=3(6 / 2) = 3
  • (18/3)=6(18 / 3) = 6
Final value is 6.

More questions on Stacks & Queues

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free