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

2018

Consider the following C code. Assume that the unsigned long int type 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 fun is called with input 240 is

Answer: B. 5Concept: In an integer loop that repeatedly assigns x = x/2 while x > 1, each iteration halves x using integer division, and the loop stops as soon as x > 1…

  1. A.

    4

  2. B.

    5

  3. C.

    6

  4. D.

    40

Attempted by 105 students.

Show answer & explanation

Correct answer: B

Concept: In an integer loop that repeatedly assigns x = x/2 while x > 1, each iteration halves x using integer division, and the loop stops as soon as x > 1 becomes false. For x = 2k, this takes exactly k iterations.

Application:

  1. With n = 240, the first loop runs 40 times. Its final update makes i = 1, so the guard i > 1 becomes false; therefore j = 40.

  2. The second loop starts at j = 40. Its five body executions update j as 40 → 20 → 10 → 5 → 2 → 1, so sum becomes 5.

Cross-check: log2(⌊log2(240)⌋)⌋ = ⌊log2(40)⌋ = 5. Hence the function returns 5.

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…