GATE 2014 (CS02) – C Programming | Q.10
Solution
🔍 Let’s trace the function carefully and understand what happens inside the while loop.
The statement uses the right-shift operator together with the assignment operator.
In simple words, shift the bits of num one position to the right and store the result back in num.
A right shift by 1 bit moves every bit one position to the right. For a positive integer, this is equivalent to dividing the number by 2, with the remainder discarded.
First, let’s convert 435 into its binary representation.
This is important because every right shift by 1 bit removes one bit from the right side of the binary number.
How to Convert 435 to Binary
To convert a decimal number into binary, we check the powers of 2 from the largest to the smallest.
The powers of 2 that we need are:
The Simple Rule
At every step, ask:
If YES, write 1 and subtract that
power of 2.
If NO, write 0 and do not subtract anything.
Step-by-Step Conversion
1. Check 256:
435 ≥ 256 → 1
435 − 256 = 179
2. Check 128:
179 ≥ 128 → 1
179 − 128 = 51
3. Check 64:
51 < 64 → 0
We cannot subtract 64 because 64 is larger than the
remaining number 51.
Remaining number = 51
4. Check 32:
51 ≥ 32 → 1
51 − 32 = 19
5. Check 16:
19 ≥ 16 → 1
19 − 16 = 3
6. Check 8:
3 < 8 → 0
We cannot subtract 8.
Remaining number = 3
7. Check 4:
3 < 4 → 0
We cannot subtract 4.
Remaining number = 3
8. Check 2:
3 ≥ 2 → 1
3 − 2 = 1
9. Check 1:
1 ≥ 1 → 1
1 − 1 = 0
Why does 51 < 64 give 0?
This is the important part to understand.
After using 256 and 128, we have 51 left. The next power of 2 is 64.
We cannot use 64 because 64 is larger than the remaining number 51.
Therefore, we write 0 for 64 and keep the remaining number as 51.
The 0 simply means:
Final Result
256 128 64 32 16 8 4 2 1
1 1 0 1 1 0 0 1 1
435 = 110110011₂
Remember:
YES → write 1 and subtract.
NO → write 0 and do not subtract.
A common way to convert a decimal number into binary is to repeatedly divide the number by 2 and record the remainder at each step.
So, 435 requires 9 binary bits. This will help us understand why the while loop in the given function executes 9 times.
| Iteration | num |
|---|---|
| Start | 435 |
| 1 | 217 |
| 2 | 108 |
| 3 | 54 |
| 4 | 27 |
| 5 | 13 |
| 6 | 6 |
| 7 | 3 |
| 8 | 1 |
| 9 | 0 |
Therefore, the loop runs 9 times before num becomes 0.
Therefore:
and the function returns:
This function counts how many bits are needed to represent a positive integer in binary.
For 435:
The binary representation of 435 contains 9 bits. Therefore, func(435) returns 9.
Exam Shortcut
Whenever you see:
directly use:
The floor function removes the decimal part and gives the greatest whole number less than or equal to the given number.
For example: floor(3.8) = 3 and floor(5.2) = 5.
For 435:
Therefore:

