# Piece of C code

#### nanobyte

Joined May 26, 2004
120
I am trying to write a C program with a Array of 6 elements where the number of bits of the value in each element is counted and added to the sixth element of the array. Would the piece of code I have below work?

int Array[5];
int i,b,x,y;

for(i=0; i<5; i++)
{
for(b=0; b<8; b++)
{
x=Array;
y=x&1;
Array[5]=Array[5]+y;
x>>1;
}
}

#### mOOse

Joined Aug 22, 2007
20
Rich (BB code):
int Array[5];
int i,b,x,y;

for(i=0; i<5; i++)
{
for(b=0; b<8; b++)
{
x=Array;
y=x&1;
Array[5]=Array[5]+y;
x>>1;
}
}


Firstly, you should not access location Array[5], as it does not exist.
Remember that reserving 5 locations gives access to offsets 0, 1, 2, 3, and 4 only.
The best fix here is to use a new variable, "total", to hold the sum.
Also, you need to initialize the Array with some numbers.

Secondly, you must assign Array to x before the inner loop, otherwise
you re-initialize x every time and you end up summing bit 0 eight times
on each array element.

Lastly, you need to use x >>= 1 to assign the result to x (this is equivalent
to x = x >> 1);

So, I haven't tested it, but something like this:

Rich (BB code):
int Array[5] = {1,2,3,4,5};  /* contains 7 bits */
int i, b, x;
int total = 0;

for (i = 0; i < 5; i++) {
x = Array;
for (b = 0; b < 8; b++) {
total += x & 1;
x >>= 1;
}
}


#### mOOse

Joined Aug 22, 2007
20
Here's a JScript version that seems to work.
Save it as a file with a .htm or .html ending and open it like a webpage.
It adds the bits in the first 10 integers ( = 17 ).

Rich (BB code):
<script>
var a = new Array(1,2,3,4,5,6,7,8,9,10);
var i, b, x;
var total = 0;
for (i = 0; i < a.length; i++) {
x = a;
for(b = 0; b < 8; b++)   {
total += x & 1;
x >>= 1;
}
}
document.writeln(total);
</script>