The GATE Grind

GATE 2017 CS – Question 65

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

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);
}

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 23

Explanation

The static variable `count` keeps growing, adding the number of 1 bits of each argument, and `total` returns the running total. The calls are for $i = 5, 4, 3, 2, 1$ with bit counts 2, 1, 2, 1, 1. So `count` becomes 2, 3, 5, 6, 7, and `x` accumulates $2 + 3 + 5 + 6 + 7 = 23$.