3

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 generate a new array with 2 elements. The value of the array is taken from the array above, and placed into the array with 2 elements. Like in the code sample 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 output 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 through the array and take the next two values and place them in the packet array and so on, until the last element in the array.

200_success
  • 7,286
  • 1
  • 43
  • 74
AdiT
  • 539
  • 5
  • 18

3 Answers3

2

You can run through the big array, and select the values to be copied in the little array, resseting j to zero when it is equal to 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));
  }
}
Bertrand125
  • 904
  • 6
  • 13
2

Use the 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));
}
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
2

Already there have been many interesting solutions posted here.Yet i would like to add one more. You can use xor operator also. c=c^1 flips the value of c between 0 and 1.when c=0,c^1=1 and when c=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.Happy coding!!

aakansha
  • 695
  • 5
  • 18