The output of executing the following C program is _______________ .…
2017
The output of executing the following C program is _______________ .
#include<stdio.h>
int total(int v) {
static int count = 0;
while(v) {
count += v&1;
v >>= 1;
}
return count;
}
void main() {
static int x=0;
int i=5;
for(; i>0; i--) {
x = x + total(i);
}
printf("%d\n", x);
}
Attempted by 100 students.
Show answer & explanation
Correct answer: 23
Answer: 23
Key point: The variable that counts bits inside the total function is declared static, so it keeps its value between calls. Each call adds the number of set bits of its argument to that persistent counter, and the function returns the cumulative total so far.
Call with 5 (binary 101): adds 2 set bits. Cumulative count becomes 2. Function returns 2. x becomes 2.
Call with 4 (binary 100): adds 1 set bit. Cumulative count becomes 3. Function returns 3. x becomes 2 + 3 = 5.
Call with 3 (binary 11): adds 2 set bits. Cumulative count becomes 5. Function returns 5. x becomes 5 + 5 = 10.
Call with 2 (binary 10): adds 1 set bit. Cumulative count becomes 6. Function returns 6. x becomes 10 + 6 = 16.
Call with 1 (binary 1): adds 1 set bit. Cumulative count becomes 7. Function returns 7. x becomes 16 + 7 = 23.
Therefore the program prints 23.