Piece of C code

Discussion in 'Programmer's Corner' started by nanobyte, Sep 11, 2007.

  1. nanobyte

    Thread Starter Senior Member

    May 26, 2004
    118
    1
    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;
    }
    }
     
  2. mOOse

    Member

    Aug 22, 2007
    20
    0
    Code ( (Unknown Language)):
    1.  
    2. int Array[5];
    3. int i,b,x,y;
    4.  
    5. for(i=0; i<5; i++)
    6. {
    7.   for(b=0; b<8; b++)
    8.   {
    9.     x=Array[i];
    10.     y=x&1;
    11.     Array[5]=Array[5]+y;
    12.     x>>1;
    13.   }
    14. }
    15. [/i]


    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:

    Code ( (Unknown Language)):
    1.  
    2. int Array[5] = {1,2,3,4,5};  /* contains 7 bits */
    3. int i, b, x;
    4. int total = 0;
    5.  
    6. for (i = 0; i < 5; i++) {
    7.   x = Array[i];
    8.   for (b = 0; b < 8; b++) {
    9.     total += x & 1;
    10.     x >>= 1;
    11.   }
    12. }
    13. [/i]
     
  3. mOOse

    Member

    Aug 22, 2007
    20
    0
    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 ).

    Code ( (Unknown Language)):
    1.  
    2. <script>
    3. var a = new Array(1,2,3,4,5,6,7,8,9,10);
    4. var i, b, x;
    5. var total = 0;
    6. for (i = 0; i < a.length; i++) {
    7.   x = a[i];
    8.   for(b = 0; b < 8; b++)   {
    9.     total += x & 1;
    10.     x >>= 1;
    11.   }
    12. }
    13. document.writeln(total);
    14. </script>
    15. [/i]
     
Loading...