edited by
638 views
1 votes
1 votes
Consider the following foo function and identify the return value of foo function.

int foo (unsigned int n)

{

            int c, x = 0;

            while (n! = 0)

            {

                        if (n & 01) x++;

                        n >>= 1;

}

return x;

}

(a) It counts the total number of bits set in an unsigned integer.

(b) It counts the number of bits which are zero.

(c) It counts the number of occurrences of 01.

(d) It returns the same value as ‘n’.
edited by

1 Answer

2 votes
2 votes
say n= 1101

now if n&01 means we will do bitwise and with n and 1.i.e,

1101 & 0001 ..now in this example the unit's place of n has 1 so 1&1 will give 1 here and hence if(1) will be true so we will increment x by 1.

now n>>=1 means n=n>>1 so will do right shift on n until n is completely exhausted i.e, n becomes 0000. so

according to our example,

1st right shift : 0110 & 0001 => 0 as 0&1 is 1=0 so x will remain 1

2nd right shift: 0011 & 0001=> 1 and x is now 2

3rd right shift: 0001 & 0001 =>1 and x is now 3

4th right shift: n becomes 0000 so while(n!=0) condition fails and we exit from the loop..

now x=3 i.e the total no of set bits or 1 in i/p stream so ans is A

Related questions

0 votes
0 votes
2 answers
2
Sk Jamil Ahemad asked Feb 1, 2022
347 views
Please explain with some example that How Right to Left associativity takes place in case of Ternary operators?
7 votes
7 votes
3 answers
3
Parshu gate asked Nov 20, 2017
780 views
What is the output of the following program?#include<stdio.h int main() { int array[]={10, 20, 30, 40}; printf(“%d”, -2[array]); return 0; }$-60$$-30$$60$Garbage valu...
0 votes
0 votes
1 answer
4
Mak Indus asked Dec 17, 2018
309 views
Let a, b be two positive integers, which of the following options correctly relates / and %?(a) b= (a/b) * b + a%b (b) b= (...