# Reverse contents of array

• 09-25-2011
Reverse contents of array
I found this algorithm to reverse the contents of an array-
Code:

```int len=strlen(word);     for (int i=0;i<len/2;i++)     {         word[i]^=word[len-i-1];         word[len-i-1]^=word[i];         word[i]^=word[len-i-1];     }```
But I really don't understand how it works. It looks as though the loop only traverses half of the array. If anyone could lend some insight I would appreciate it.
• 09-25-2011
laserlight
What does the code in the loop body do?
• 09-25-2011
It is supposed to reverse the contents of an array, that is take 4689 and turn it into 9864, using XOR operations.

I found the algorithm here
http://stackoverflow.com/questions/1...129028#1129028
• 09-25-2011
Salem
Make word an array of doubles, or pointers, or structs, and see how far it gets you.
Question 3.3b
• 09-25-2011
laserlight
Yes, but I am asking you specifically about the loop body, i.e.,
Code:

```word[i]^=word[len-i-1]; word[len-i-1]^=word[i]; word[i]^=word[len-i-1];```
That said, now that I took a good look myself, I think you should examine this example instead:
Code:

```int len = strlen(word); for (int i = 0; i < len / 2; i++) {     char temp = word[i];     word[i] = word[len - i - 1];     word[len - i - 1] = temp; }```
The same question applies: what does the loop body do? Once you answer this correctly, you are on your way to answering your own question of why "the loop only traverses half of the array".
• 09-25-2011
I figured it out; were swapping the first and last elements, then second and second to last element, etc. which means that we only need to go half way through the array to reverse the elements.
• 09-25-2011
laserlight
Yes, that is correct :)