Reputation: 40496
I need to reverse large arrays such that the first element becomes the last, and the last becomes the first.
Until now I did this by creating a copy of this array, then iterate backwards over the original and write to the copy. After that, write the copy back to the original.
Is it possible to do this safely in one single loop by simultaneous access to the first and last element, storing one of them in a temp var and swapping the values?
Upvotes: 0
Views: 3779
Reputation: 1
You can use reverse() function or I think this will be very easy solution
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
unsigned int arr[n];
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}
while(n)
{
cout<<arr[n-1]<<" ";
n--;
}
return 0;
}
Upvotes: 0
Reputation: 12496
int Array[100];
unsigned int i, j;
for (i=0, j=100-1; i<j; i++, j--)
{
int t;
t = Array[j];
Array[j] = Array[i];
Array[i] = t;
}
Upvotes: 2
Reputation: 8207
For integer types a better way is...
int arr[5]={1,2,3,4,5};
int c=0,d=sizeof(arr)/sizeof(*arr)-1;
for(;c<d;c++)
{
arr[c] ^= arr[d-c];
arr[d-c] ^= arr[c];
arr[c] ^= arr[d-c];
}
since XOR is one byte instruction, it will take hardly 3 byte along the swap line .
Upvotes: 3