Question:
Write the definition of a function reverse , whose first parameter is an array of integers and (continued)?
kosmic_chic
2011-04-26 04:13:42 UTC
language: C++
Question:
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 the array. The function reverses the elements of the array. The function does not return a value.

I don't understand where I'm going wrong in this one... I will appreciate any help. Here is what I have so far:
void reverse( int array[], int size)
{
int x, y = 0;
for (x = 0; x < size; x++)
{
y = array[x];
array[x] = array[size - 1 - x];
array[size - 1 - x] = y;
}
}
Four answers:
videobobkart
2011-04-29 00:55:33 UTC
The above answer is okay, although it would be better if it used some C++-only constructs, like reference parameters in the swap function for example.



Your code can be fixed by just looping up to size/2 instead of size. You're reversing it *twice* by going too far, ending up where you started. Think about it: on the run up from 0 to size/2, you exchange elements from the first half of the array with corresponding elements in the second half. If you stopped there you'd be done, but since your loop goes all the way to size, you then exchange elements from the *second* half of the array with corresponding elements in the *first* half, undoing the earlier exchanges.
?
2017-01-19 01:30:08 UTC
1
?
2016-07-29 18:52:50 UTC
void reverse( int array[], int size)

{

int x, y = 0;

for (x = 0; x < size/2; x++)

{

y = array[x];

array[x] = array[size - 1 - x];

array[size - 1 - x] = y;

}

}
anonymous
2011-04-26 07:04:52 UTC
void swap(int *x, int *y)

{

int tmp;



tmp = *x;

*x = *y;

*y = tmp;

}



void rev(int arr[], int size)

{

int i;



for(i = 0; i < size / 2; ++i)

swap(&arr[i], &arr[(size - 1) - i]);

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Search results for 'Write the definition of a function reverse , whose first parameter is an array of integers and (continued)?' (Questions and Answers)
4
replies
acessing cached pages?
started 2006-07-07 05:56:14 UTC
computers & internet
Loading...