Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

GATE | GATE-CS-2017 (Set 1) | Question 64

  • Difficulty Level : Medium
  • Last Updated : 31 Aug, 2021

The output of executing the following C program is ________.

# include 

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

(A) 23
(B) 24
(C) 26
(D) 27


Answer: (A)

Explanation: Digits : 5-0101, 4-0100, 3-0011, 2-0010, 1-0001
Countof 1s : 2, 3, 5, 6, 7

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

Total: 2+3+5+6+7 = 23



total(i)=23

Therefore, option A is correct

Check out the running code with comments:




#include<stdio.h>
  
int total(int v) 
{
    static int count = 0;
    while(v) 
    {
        count += v&1;
        v >>= 1;
    }
      
    //This count can be used to see number of 1s returned
    //for every number i
    //printf("%d", count);
    return count;
}
  
void main() 
{
    static int x=0;
    int i=5;
    for(; i>0; i--) 
    {
        //total gets added everytime with total number
        //of digits in the given number i
        x = x + total(i);
    }
    printf("%d\n", x);
}



Alternate Solution :
g-set1_a64



This solution is contributed by parul sharma

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!