The GATE Grind

GATE 2018 CS – Question 42

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

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 $2^{40}$ is

  1. 4
  2. 5
  3. 6
  4. 40

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (B) 5

Explanation

The first loop halves $n=2^{40}$ until it reaches 1, so $j=40$. The second loop halves $j$: $40\to20\to10\to5\to2\to1$ and increments `sum` 5 times.