831 views
0 votes
0 votes

#include <stdio.h>

int total(int v)
{
static int count=0;
while(v){
	count+=v&1;
	v>>=1;
}
return count;
}


void main() {
	// your code goes here
	static int x=0;
	int i=5;
	for(;i>0;i--)
	{
		x=x+total(i);
	}
	printf("%d\n",x);
	return 0;
}

2 Answers

0 votes
0 votes
for(i=5;i<0;i--)

{

  x=x+total(i);

}

 

x is going to get added for every iteration as it is static variable

 

Now,

for total(5)

{

5 can be represented in binary as 0101

so Anding 5 with 1 will give the answer for first iteration

and it will get added to count        //count=1

Next, for bitwise right shift

the number will become 0010

Anding this number with 1 will give us 0    //count=1

so count will not get incremented

for next bitwise right shift

the number will become 0001

Anding this number with 1 will give us 1

So count will get incremented     //count=2

}

 

This is for first function call total(5)

so x will have value 2 for first iteration

similarly for

total(4)

count will have value 3 // Remember count is static variable and it will not be vanished

x will have value 2+3=5 after second iteration

similarly for

total(3)

count will have value 5 // Remember count is static variable and it will not be vanished

x will have value 2+3+5=10 after third iteration

similarly for

total(2)

count will have value 6 // Remember count is static variable and it will not be vanished

x will have value 2+3+5+6=16 after fourth iteration

 

similarly for

total(1)

count will have value 7 // Remember count is static variable and it will not be vanished

x will have value 2+3+5+6+7 after fifth iteration

 

Hence, value of x will be 23
reshown by

No related questions found