GATE / CS ARCHIVE

GATE CSE 2017 SET 1 / QUESTION 55

GATE CSE 2017 Set 1 Q55

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2017 Set 1 paper

GATE 2017 Set 1, Q55 2 marks · NAT
Report issue

Scope, Lifetime & Storage Classes

Question 55, GATE 2017: #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); }
Find printed output.
Tap to enlarge
Answer & solution

Official answer: 23.0

Our answer: 23

1. Inside total, v&1 extracts the low bit and v>>=1 removes it. The loop counts set bits, but count is static: its value persists across different calls.

2. Arguments are 5,4,3,2,1, with binary forms 101,100,11,10,1 and popcounts 2,1,2,1,1. Therefore total returns cumulative counts 2,3,5,6,7, rather than the individual popcounts.

3. main adds each returned value to its own x: 2, then 5,10,16,23. The final output is 23. Resetting count on each call would wrongly give 7.

void main is a nonstandard hosted-C entry point; the exam assumes an implementation accepting it.

Original paper, page 24 · Answer key