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