Consider the function func shown below:
int func(int num) {
int count = 0;
while (num) {
count++;
num>>= 1;
}
return (count);
}
The value returned by func() is ________
View worked solution
Answer: 9
The given function func(num) counts the number of bits in the binary representation of the positive integer num by repeatedly right-shifting it by 1 bit (which is equivalent to integer division by 2) until num becomes 0.
Mathematically, the value returned for any positive integer is given by:
For :
- We know that and .
- Since , the binary representation of requires exactly bits.
Let's trace the loop step-by-step:
| Iteration | Initial num (Decimal) |
count (After increment) |
Next num (After num >>= 1) |
|---|---|---|---|
| 1 | 435 | 1 | 217 |
| 2 | 217 | 2 | 108 |
| 3 | 108 | 3 | 54 |
| 4 | 54 | 4 | 27 |
| 5 | 27 | 5 | 13 |
| 6 | 13 | 6 | 6 |
| 7 | 6 | 7 | 3 |
| 8 | 3 | 8 | 1 |
| 9 | 1 | 9 | 0 |
When num becomes 0, the while loop terminates, and the function returns count, which is 9.
Free practice · Your answers on this page are not saved.
