Skip to main content

GATE CSE 2018Programming in C › General C Programming ConceptsVerified

GATE CSE 2018 PYQ: Consider the following C code. Assume that unsigned long int type length is 64 64 64 bits. unsigned long int…

Consider the following C code. Assume that unsigned long int type length is 64 bits.

unsigned long int fun(unsigned long int n) {
        unsigned long int i, j=0, sum = 0;
        for( i=n; i>1; i=i/2) j++;
        for( ; j>1; j=j/2) sum++;
        return sum;
}

The value returned when we call fun with the input 2402^{40} is:

  1. A
    4
  2. B
    5
    Correct answer
  3. C
    6
  4. D
    40

Answer

(B) 5 5 5

Approach

Trace the two independent loops. The first loop determines how many times n can be halved before reaching 1, giving j = floor(log2 n). The second loop determines how many times j can be halved before reaching 1, giving the returned sum.

The first loop computes j = $floor(log2(2^40)) = 40$. The second loop computes the number of times 40 can be halved until it is no longer greater than 1: 40 → 20 → 10 → 5 → 2 → 1, which is 5 increments. Thus the returned value is 5, option B.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.