Can anyone fix this code and explain me why 11 is coming | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone fix this code and explain me why 11 is coming

https://code.sololearn.com/cZ2r9KzRPpMJ/?ref=app

7th Nov 2019, 9:58 AM
Preity
Preity - avatar
4 Answers
+ 2
What the `value` function do is to count the total number of `1` in each element of the array. For example, the first element of the array is 3(dec)=0011(bin), in the `while` loop, for 1st time, *x is 3(0011) *x & 1 = 0011 & 0001 = 0001 = 1 so count = 0 + 1 = 1 then `*x>>=1` will make the value shift one bit to the right, and you will get 0001(from 0011 shift one bit to the right). 2nd time in the `while` loop, *x is 0001 *x & 1 = 0001 & 0001 = 0001 = 1 so count = 1 + 1 = 2 then after `*x>>=1` you will get 0000(from 0001 shift one bit to the right), so the loop ends. For 5(dec)=0101(bin), there are two `1`. For 6(dec)=0110(bin), there are two `1`. For 4(dec)=0100(bin), there is one `1`. Because `count` is static, so you will get the sum to 7(2+2+2+1). In the `for` loop, the last time `a[y]` is 4, so z = 4 + 7 = 11. .
7th Nov 2019, 11:13 AM
o.gak
o.gak - avatar
+ 3
o.gak Avinesh thanks for explaining 👍
7th Nov 2019, 2:06 PM
Preity
Preity - avatar
+ 1
Preity here you are using a static variable inside the function which is initialized to 0 by itself and retains it's value in every function call. So when you pass each element of the array to the function one by one, the count value gets updated everytime. So at last the count becomes 7 and a[y] which is a[3] is 4 are summed to get the resultant output of 11.
7th Nov 2019, 10:54 AM
Avinesh
Avinesh - avatar
0
~ swim ~ please give explanation for this why 11 is coming
7th Nov 2019, 10:09 AM
Preity
Preity - avatar