# reverse the order of an array

• 01-22-2003
dustyd
reverse the order of an array
Hello can anyone give me some advice on how to reverse the order of an array for example say in my array i had the values
9 8 7 6 5 4 3 2 1... how can i get it to be
1 2 3 4 5 6 7 8 9.

i tryed
for (x=sizeOfArray; x>=0; x--)
{ for (y=0; y<=sizeOfArray;y++)
{ tmp1[y] = tmp2 [x];
}
}
where tmp2 is the array that holds the original values and tmp1 will store the reverse image...for some reason it is not working can any one confrim the code or assist me in correcting it.

Thanks:(
• 01-23-2003
carrja99
pretty simple really. There are several ways to do this, one way would be to sort the array, another would be to swap values until it reaches the center. for example:

Code:

```temp_size = array_size - 1; for (int i = 0; i < array_size; i++)     {     if (i != temp_size)         {temp = a[i];         a[i] = a[temp_size];         a[temp_size] = temp;         temp_size--;         }     }```
This is just a small untested example. You should probably experiment with it a bit, or use it as an example to build off of.
• 01-23-2003
ripper079
Two lines :D

Code:

```for (int i = sizeof(array)/sizeof(array[0])-1, int x = 0; i > -1; i--, x++)                 reversearray[x] = array[i];```
However when I compiled this code the compiler complained(warning) about "nonstandard extension used" but from where I can see it is standard (maybe someone can confirm this). Anyway if you dont like this warning just move the first statement ( int i = sizeof(array)/sizeof(array[0])-1, int x = 0 ) before the for-loop and it should compile "correct".
• 01-23-2003
lurker
I don't think you need the 'y' for loop. I think this may work:

Code:

```y=0; for (x=sizeOfArray-1; x>=0; x--)   {   tmp1[y] = tmp2 [x];   y++;   }```
I changed the 'x=' to 'x=sizeOfArray-1. If the size of the array is 10, the last element of it will be 9. I haven't compiled or tested this, but I think it may be o.k.
• 01-23-2003
grib
one line :D
Code:

`std::reverse(array,&array[size_of_array]);`
ok, you need to include <algorithm>, but still.

edit: the OP may have wanted
Code:

`std::reverse_copy(tmp1,tmp1[size_of_array],tmp2);`
assuming tmp2 is big enough