Skip to content
Official PYQ · 2018

GATE CS 2018 Q32 — Programming in C

Explain with AI

Consider the following C code. Assume that unsigned long int type length is 6464 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:

Choose one option
View worked solution

Answer: B

To find the value returned by fun(2^{40}), let's analyze the two loops step-by-step.

Step 1: Analyzing the First Loop

for( i=n; i>1; i=i/2) j++;

This loop starts with i=n=240i = n = 2^{40} and repeatedly divides ii by 22 until i≤1i \le 1. Since ii is halved in each step, the loop runs exactly log⁡2(n)\log_2(n) times.

  • For n=240n = 2^{40}, the loop executes 4040 times.
  • Therefore, the value of jj after the first loop terminates is 4040.

Step 2: Analyzing the Second Loop

for( ; j>1; j=j/2) sum++;

This loop starts with the current value of j=40j = 40 and repeatedly divides jj by 22 (using integer division) until j≤1j \le 1. Let's trace the iterations:

Iteration Current jj (j>1j > 1) New sum Next jj (after j = j/2)
1 40>140 > 1 (True) 11 2020
2 20>120 > 1 (True) 22 1010
3 10>110 > 1 (True) 33 55
4 5>15 > 1 (True) 44 22 (integer division)
5 2>12 > 1 (True) 55 11
6 1>11 > 1 (False) Loop terminates

When the loop terminates, the value of sum is 55, which is returned by the function.

Thus, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions