GATE / CS ARCHIVE

GATE CSE 2024 SET 1 / QUESTION 33

Parse arithmetic with unusual precedence

Programming in C · Expressions, Operators & Types · Full GATE CSE 2024 Set 1 paper

GATE 2024 Set 1, Q33 1 mark · NAT
Report issue

Expressions, Operators & Types

Question 33, GATE 2024: Evaluate 3+1+5*2/7+2−4−7−6/2 using these rules: + has highest precedence and associates left; − is next and associates right; * is next and associates right; / is lowest and associates right. All arithmetic is integer arithmetic.
Tap to enlarge
Answer & solution

Official answer: 6

Approach: Build the grouping from the stated table, not from ordinary mathematical or C precedence. Associativity decides grouping only among operators at the same precedence.
1. Highest-precedence additions group (3+1+5)=9 and (7+2)=9. The expression becomes 9*2/9−4−7−6/2.
2. Subtraction has higher precedence than multiplication and division and is right-associative. Its group is 9−(4−(7−6)). Evaluate inward: 7−6=1, 4−1=3, 9−3=6.
3. The expression is now 9*2/6/2. Multiplication is next, giving 18/6/2.
4. Division is right-associative, so this means 18/(6/2), not (18/6)/2. The inner quotient is 3 and the result is 18/3=6.
Answer: 6. A fully parenthesized form is ((3+1)+5)*2 / (((7+2)−(4−(7−6)))/2). Both actual divisions are exact, so no integer-rounding issue arises.

Original paper, page 20 · Answer key