Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q55 — Programming in C

Explain with AI

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);
}
View worked solution

Answer: 23

To find the output of the program, let's analyze the behavior of the function total(int v) and the loop in main().

1. Analysis of total(int v)

  • The variable count is declared as static int count = 0;. This means its value is retained across multiple function calls.
  • The while(v) loop counts the number of set bits (1s) in the binary representation of v using the bitwise AND operator (v & 1) and right shift operator (v >>= 1).
  • This count of set bits is accumulated into the static variable count, and the updated value of count is returned.

2. Step-by-Step Execution Trace

The loop in main() runs for i=5,4,3,2,1i = 5, 4, 3, 2, 1. The variable x is initialized to 00.

Iteration (ii) Binary of ii Set Bits in ii New count (accumulated) Value returned by total(i) Updated x=x+total(i)x = x + \text{total}(i)
5 101 2 0+2=20 + 2 = 2 2 0+2=20 + 2 = 2
4 100 1 2+1=32 + 1 = 3 3 2+3=52 + 3 = 5
3 011 2 3+2=53 + 2 = 5 5 5+5=105 + 5 = 10
2 010 1 5+1=65 + 1 = 6 6 10+6=1610 + 6 = 16
1 001 1 6+1=76 + 1 = 7 7 16+7=2316 + 7 = 23

After the loop terminates, the program prints the value of x, which is 23.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions