Write a function that accepts an array of integers and an integer that represents the size of the array. This function will reverse the order of the array. Ex:
if a[0] = 4, a[1] = 2, a[2] = 9, a[3] = 89;
After executing this function:
a[0] = 89, a[1]=9, a[2] = 2, a[3] = 4
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
const int SIZE = 4;
int a[4] = {4, 2, 9, 89};
for (int count = 0; count %26lt; SIZE; count++)
b[count] = a[count];
return 0;
}
I have this so far, I can't get any farther, can u please make some changes.
Beginner C++ help plz?
This is a very very common question especially on job interviews so it is important that you have as an elegant as solution as possible.
void Reverse(int* array, int length)
{
int i, tmp;
for (i=0; i%26lt;len/2; i++)
{
tmp = array[i] ;
array[i] = array[len-i-1] ;
array[len-i-1] = tmp;
}
note there is an even more elegant solution using the ^ (xor) operation but that is not for the beginner.
**** Note I edited the second line from
array[i] = tmp
to
array[len-i-1]
}
Reply:What do you need to do here honey? What does b[count]=a[count] do ? It makes and exact copy of the array, right?
Whare you want to do is flip the array. You want that line to be something like this:
b[count]=a[SIZE-count];
This may look wrong at first, but try it out, you will be plesantly surprised.
Do the math for it and you will see what is happening.
b[0]=b[4-0]
b[1]=b[4-1]
and so on....
:)
Actually I also like the other guys answer for this one, that is a much more elegant solution.
cheap flowers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment