GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 32

Two integer-halving loops

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2018 paper

GATE 2018, Q32 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 32, GATE 2018: A 64-bit unsigned-long function initializes j=sum=0. It runs for(i=n;i>1;i=i/2) j++; then for(;j>1;j=j/2) sum++; returns sum. For n=2^40, choose A 4; B 5; C 6; D 40.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Method

The first loop sees i=2^40,2^39,…,2 before stopping at i=1, so its body runs 40 times. The second loop then uses integer division: 40→20→10→5→2→1. It executes for the first five of these values, not for the final 1. The two loops are consecutive, not nested: multiplying their iteration counts would not describe the return value. The exponent in 2^40 is essential and can be lost in text extraction.

Solution

The first loop halves i until 1, performing 40 iterations, hence j=40. The second loop has j values 40, 20, 10, 5, 2 before stopping at 1, so sum=5, B.

Original paper, page 13 · Answer key