# Thread: Reverse contents of array

1. ## 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.

2. What does the code in the loop body do?

3. 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

4. Make word an array of doubles, or pointers, or structs, and see how far it gets you.
Question 3.3b

5. 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".

6. 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.

7. Yes, that is correct

Popular pages Recent additions