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 vv (Hamming weight) and adds it to count.

The function main() runs a loop for i=5,4,3,2,1i = 5, 4, 3, 2, 1:

  • i=5i = 5 (binary 101, weight = 2):
    count becomes 0+2=20 + 2 = 2. total(5) returns 2.
    x=0+2=2x = 0 + 2 = 2.
  • i=4i = 4 (binary 100, weight = 1):
    count becomes 2+1=32 + 1 = 3. total(4) returns 3.
    x=2+3=5x = 2 + 3 = 5.
  • i=3i = 3 (binary 011, weight = 2):
    count becomes 3+2=53 + 2 = 5. total(3) returns 5.
    x=5+5=10x = 5 + 5 = 10.
  • i=2i = 2 (binary 010, weight = 1):
    count becomes 5+1=65 + 1 = 6. total(2) returns 6.
    x=10+6=16x = 10 + 6 = 16.
  • i=1i = 1 (binary 001, weight = 1):
    count becomes 6+1=76 + 1 = 7. total(1) returns 7.
    x=16+7=23x = 16 + 7 = 23.

The loop finishes when i=0i = 0. printf outputs x=23x = 23.

Final answer

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.