Question
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);
}Official answer and solution
- Official answer
- 23
- From
- Official GATE 2017 answer key
Solution
Trace the execution of total() noting that the static variable count retains its value across successive loop calls.
In function total(v):
int total(int v) {
static int count = 0;
while (v) {
count += v & 1;
v >>= 1;
}
return count;
}
Because count is declared static, it is initialized to 0 once and preserves its accumulated value across successive calls. The loop counts the number of 1s in the binary representation of (Hamming weight) and adds it to count.
The function main() runs a loop for :
- (binary
101, weight = 2):
countbecomes .total(5)returns 2.
. - (binary
100, weight = 1):
countbecomes .total(4)returns 3.
. - (binary
011, weight = 2):
countbecomes .total(3)returns 5.
. - (binary
010, weight = 1):
countbecomes .total(2)returns 6.
. - (binary
001, weight = 1):
countbecomes .total(1)returns 7.
.
The loop finishes when . printf outputs .
23.0
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 1
- Question
- 55 of 65, printed as CS Q.55
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.