# Thread: Reversing elements in an array

1. ## Reversing elements in an array

This is technically a homework question but it's already past due. I'm trying to understand the answer as I got stuck trying to complete it.

Write the definition of a function reverse , whose first parameter is an array of integers and whose second parameter is the number of elements in thearray . The function reverses the elements of the array . The function does not return a value .

Code:
```void reverse(int a[], int num)
{
for ( int i=0; i <= num/2 ; i++){
int temp = a[i];
a[i] = a[num-i-1];
a[num-i-1] = temp;
}

}```
This is supposed to be the answer but I'm not quite sure why this is. I understand everything up until the actual loop. For one, shouldn't "int i" be declared outside the loop (I thought perhaps this was an error in the solutions)?

The main thing that I do not understand is the conditional statement.
Code:
`i<=num/2;`
This is what is confusing me. I don't understand why the "num/2" is necessary here. Also I can't really remember but is there a command that actually reverses an array for you? I vaguely recall my professor mentioning something about it but maybe I misunderstood.

2. Originally Posted by supermcbrownie
whose first parameter is an array of integers
Technically, that parameter is a pointer to the first element of an array of integers.

Originally Posted by supermcbrownie
shouldn't "int i" be declared outside the loop
No, declaring it like that is fine, at least when compiling with respect to the 1999 edition of the C standard or later. It means that the scope of i is within the loop, but not after. Since i is not used after the loop, there is no problem.

Originally Posted by supermcbrownie
This is what is confusing me. I don't understand why the "num/2" is necessary here.
Suppose you want to reverse the elements of an array of 5 integers:
Code:
`0 1 2 3 4`
So, num == 5, num / 2 == 2. We start by swapping the elements at i == 0 and i == 4:
Code:
`4 1 2 3 0`
Then we swap the elements at i == 1 and i == 3:
Code:
`4 3 2 1 0`
Now, i == 2. So, we stop. But what if we continue?
Code:
`4 3 2 1 0`
Okay, swapping the element at i == 2 and i == 2 didn't change anything. But still, we go on with swapping the elements at i == 3 and i == 1:
Code:
`4 1 2 3 0`
and finally, we swap the elements at i == 4 and i == 0:
Code:
`0 1 2 3 4`
and the net result is that we have not reversed the elements of the array.

3. @ Laserlight- Would that work with an array with an even number of elements?

4. Originally Posted by Alpo
@ Laserlight- Would that work with an array with an even number of elements?
Try it and find out.

5. So what exactly is that condition? If num is divisible by 2?

6. Originally Posted by supermcbrownie
So what exactly is that condition? If num is divisible by 2?
If there are an even number of elements, then all elements are swapped. If there are an odd number of elements, then all but the middle element are swapped.