Find the value of x in total(int v).
#include<stdio.h>

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

}

 

in first call from main() to   total(5)  ...

in total(5)  v is 5    ,count is 0  , , while v is not 0  : v&1 (101 & 001)gives 001 i.e 1 .. thn what  v >>=1 mean??? 

 

 

3Comments
Kavya Kamish Upadhyay @kavya8755
29 Apr 2017 06:53 pm

v=v>>1;  // 1001>>1==0100

shweta @shweta1920
29 Apr 2017 08:01 pm

v>>1     and v>1 ... are these same??? whats the difference?

Kavya Kamish Upadhyay @kavya8755
29 Apr 2017 08:44 pm

Nopes...

> is Relational Operator while >> (called as right shift) is Bitwise operator it works on bits

 

lets take an example;   assume that v=20;

it means in binary it would be    v= 10100;

than,  v>>2; means 10100>>2 ==00101 (two bits shifted towards right in )

in decimal 00101 is 5, so v>>=2; means v becomes 5   (after v=v>>2;)