Populating an array from a large array, two elements at a time

I have an array of 10 random elements generated like this:

             for ( j = 0;j<10;j++)
                {

                    file[j] = rand();

                    printf("Element[%d] = %d\n", j, file[j] );                  
                }

      

Then I create a new array with 2 elements. The array value is taken from the array above and placed in an array with two elements. As in the example code below:

         for(i = packet_count, j = 0; j < 2; ++j, ++i)
            {
                    packet[j] = file[i] ;
                    ++packet_count ;
                    printf("\npacket: %d", packet[j]);

            }
                printf("\nTransmit the packet: %d Bytes", sizeof(packet));

      

The result is shown below:

Telosb mote Timer start.
Element[0] = 36
Element[1] = 141
Element[2] = 66
Element[3] = 83
Element[4] = 144
Element[5] = 137
Element[6] = 142
Element[7] = 175
Element[8] = 188
Element[9] = 69

packet: 36
packet: 141
Transmit the packet: 2 Bytes

      

I want to run an array and take the next two values ​​and put them in a package array and so on up to the last element in the array.

+3


source to share


3 answers


You can run a large array and select the values ​​to be copied in the small array, overriding j

to zero when it is 2:



j = 0;
for(i = 0; i < 10; i++) {
  packet[j] = file[i];
  printf("\npacket: %d", packet[j]);
  j++;
  if(j == 2) { 
    j = 0;
    printf("\nTransmit the packet: %d Bytes", sizeof(packet));
  }
}

      

+2


source


Use a modulus operator. Example:



for(i = 0; i < 10; ++i)
{
    packet[i % 2] = file[i] ;
    printf("\npacket: %d", packet[i % 2]);

    if(i % 2)
        printf("\nTransmit the packet: %d Bytes", sizeof(packet));
}

      

+2


source


There have already been many interesting solutions posted here. I would like to add one more. You can also use the xor operator. c=c^1

flips the value of c between 0 and 1.after c=0,c^1=1

and whenc=1,c^1=0.

int i,c=0;
for(i=0;i<10;i++)
{
     packet[c] = file[i];         
     printf("\npacket: %d", packet[c]);
     if(c==1)
         printf("\nTransmit the packet: %d Bytes", sizeof(packet));
     c=c^1;
}

      

Hope it helps. Nice coding !!

+2


source







All Articles