GATE / CS ARCHIVE

GATE CSE 2014 SET 2 / QUESTION 10

GATE CSE 2014 Set 2 Q10

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2014 Set 2 paper

GATE 2014 Set 2, Q10 1 mark · NAT
Report issue

Control Flow & Loop Tracing

Question 10, GATE 2014: For the C function int func(int num){int count=0; while(num){count++; num>>=1;} return count;}, find func(435).
Tap to enlarge
Answer & solution

Official answer: 9

1. Set up the reasoning. The input is positive, so repeated right shifts discard low bits until the most significant 1 has also been shifted away. The return value is binary length, not population count.

2. Derive the result. For positive num, each right shift divides by 2 and discards the remainder. The sequence 435, 217, 108, 54, 27, 13, 6, 3, 1 has 9 nonzero values before 0, so the loop returns 9.

3. Check the interpretation. Since 28≤435<29, exactly nine shifts are needed. This gives a compact independent check of the explicit sequence and avoids confusing shifts-to-zero with the number of set bits.

Original paper, page 31 · Answer key