# Thread: Reverse an array

1. ## Reverse an array

Hi i have 2 function for reversing arrays. One work and the other doesn't. can help me analyse why the first is wrong?
Code:
```void reverse_array(int arr[], int length)
{
int i,j;
for(i=length; i>0; i--)
for(j=0; j<length; j++)
{
arr[j]=arr[i];
printf("%d ", arr[j]);
}
}```
The above can't work.

Code:
```void reverse_array(int arr[], int length)
{
int i, temp;
for (i=0; i<length/2; i++)
{
temp = arr[i];
arr[i] = arr[length-i-1];
arr[length-i-1] = temp;
}
}```
this works (why they use length/2 ??)

thanks!

2. Work through it by hand on a small array, say [1, 2, 3, 4, 5]. See what happens if you go stop at length/2 and what happens if you go all the way to length.

3. Originally Posted by anduril462
Work through it by hand on a small array, say [1, 2, 3, 4, 5]. See what happens if you go stop at length/2 and what happens if you go all the way to length.
Oh it is because if i swap till length, not length/2, array will still be 1,2,3,4,5?

In what kind of circumstances, should i use length instead of length/2?
what about the first code? i didnt use temp.

4. Originally Posted by wonderwall
Oh it is because if i swap till length, not length/2, array will still be 1,2,3,4,5?

Yes. You're working from both ends towards the middle (think of the relationship between i and length-i-1). If you swap length times, you swap, e.g., i = 0 with length-0-1, then when i is length-1, you swap that with length-(length-1)-1 = 0, effectively swapping everything back.

In what kind of circumstances, should i use length instead of length/2?
Not this circumstance. You will use length much more often than length/2, almost any time you need to access each element of the array (except swap, and maybe some search and sort methods).

what about the first code? i didnt use temp.
Your first code is horribly broken. The first time through your i loop, i = length (which is one element past the end of your array, so it is garbage data), your j loop assigns that garbage data to all the elements of the array.

5. What the first function does is overwrite every value with the value from every other position in the array. It looks to me like a coding-first, think-later attempt.

Popular pages Recent additions