GATE CSE 2017 Session 1 Q65: Output of C program summing total(i) with a static bit-count accumulator
- Programming and Data Structures
- 2 marks
- NAT
- No negative marking
Syllabus topic: Programming in C
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);
}Try it: numerical answer: type the value
Numerical answer. No negative marking.
Show answer and explanation
Answer: 23 (official GATE 2017 final answer key)
Concept used: total(v) adds the number of 1 bits of v to a static counter that keeps its value across calls, so each call returns a running total.
First step: Count the 1 bits in 5, 4, 3, 2, 1, keep a running sum for count after each call, and add those running sums into x.
Full step-by-step solution
Loading…
Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.
More questions on Programming in C
Every PYQ on this topic →Share this question
Source: official GATE 2017 Session 1 CS question paper and final answer key, organised by IIT Roorkee. Question paper · Answer key
More Programming and Data Structures PYQs
- 2026 Session 1 · Q23Non-leaf indices in a 1-indexed binary heap with n odd
- 2026 Session 1 · Q24Empty slots after linear-probing inserts with h(x) = (x+7) mod 11
- 2026 Session 1 · Q33Maximum height of a full binary tree with 23 nodes
- 2026 Session 1 · Q34Output of a C function with a shadowed block variable
- 2026 Session 1 · Q39Recursive length of a non-empty singly linked list
- 2026 Session 1 · Q40Third insertion that can never yield a complete BST of 1..15