628 views
1 votes
1 votes
int fun(int n)

{

int table={0,1,2,1,2,2,3,1,2,2,3,2,3,3,4};

int count =0;

for(;n;n>>4)

count=count + table[n & oxf];

return(count);

}

what will fun() return?

1.returns no.of 0's in the number

2.returns no.of 1's in the number

3.returns no.of 0's and 1's in the number

4.none

2 Answers

0 votes
0 votes
I think its 4.None

first of all right shifting on signed number is machine dependent.So assuming we are filling vacant bits with 0 after right shift operation.

oxf is 1111 in binary. So table[n & oxf] will simply be table[n] (for n less than equal to 15).

fun(0)->0 fun(1) -> 1 fun(2)-> 2 fun(3)->1 ... Can't be any of the first three of options.

Also for n = 15 we will have table[n & oxf] as table[15] which will be garbage value.

If I am not misinterpreting something then it should be option 4.
0 votes
0 votes

n>>4 is right shift operator and (n & x0f) is bitwise and operator.

f(1) n=0001 and count=0,

n&0xf : ( 0001 & 1111)=0001 therefore t[0001]=1

count=0+1=1

after shift right 4 times ...it makes 0001-->0000 and for statement will not execute.

return 1

next

f(2)

n=0010, count=0;

0010 & 1111=0010

i.e t[0010]=2;

count=0+2=2

after 0010 4 time right shift 0000 and for will not execute again.

return 2
like that f(3)=1

....doesnot match with option hence 4.

No related questions found