1,304 views

4 Answers

3 votes
3 votes
10 / 2 = 5

5 / 2 = 2, now x will be increments to 1 as the lower bit in n is now 1.

2 / 2 = 1, now x will be incremented to 2.

1/2 = 0. loop terminates.

c which is not modified anywhere will be returned. It is garbage as auto variables are not initialized in C.
0 votes
0 votes
giving eror in code blocks.....

Process returned 1995897945 (0x76F6FC59)
0 votes
0 votes
this will not give any output since c has neither been initialised nor modified anywhere.

this function is basically dividing the number by 2.
0 votes
0 votes

Dear Tariq,

I know the source from where you found this program and let me tell you that, those set of books are worst. Now coming to my answer.

That is not surprising of that book it has lots of mistakes. Therefore below is the correct program.

    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
        int n=10,y;
        y=foo(n);
        printf("%d",y);
    }
    int foo(unsigned int n)
    {
       int x=0;
        while(n!=0)
        {
            if(n&01) x++;
            n>>=1;
       }
        return x;
    }

Output: 2

Explanation

First loop:

n=10, now convert it into binary i.e. 1010. now (1010 & 0001) will be 0000. so ultimately 0. False condition.

x will remain 0.

But, n is shift right side by 1 bit i.e.  0101. (in decimal n=5)

Second Loop:

n=5, now again (0101 & 0001) will be 0001. So in decimal 1. Condition Satisfied.

Therefore x will be incremented by 1. (x=1)

n will be shifted by 1 bit. 0010. (in decimal n=2)

Third Loop:

n=2, now convert it into binary i.e. 0010. now (0010 & 0001) will be 0000. so ultimately 0. False condition.

x will remain 1.

But, n is shift right side by 1 bit i.e.  0001. (in decimal n=1)

Fourth Loop:

n=1, now again (0001 & 0001) will be 0001. So in decimal 1. Condition Satisfied.

Therefore x will be incremented by 1. (x=2)

n will be shifted by 1 bit. 0000. (in decimal n=0)

Now, (n!=0) condition is false, hence it goes out of the loop. and return x. which is printed in main().

Related questions

0 votes
0 votes
0 answers
2
shivam sharma 5 asked Aug 27, 2018
6,376 views
#include <stdio.h>void fun(int);typedef int (*pf) (int ,int );int proc(pf, int ,int);int main(){ int a = 3; fun(a); return 0; }void fun(int n){ if (n>0) ...
0 votes
0 votes
1 answer
3