View Single Post
  #2 (permalink)  
Old February 3rd, 2009, 02:22 AM
Old Pedant Old Pedant is offline
Friend of Wrox
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts

Think about what you have:

const int MAX = 5;
int arr[MAX];
So how many ELEMENTS will be IN that array???

Yes, 5.

But HOW are they NUMBERED???

Yes, zero through 4. Only.

So even your display( ) function is wrong:
void array::display()
    for (short i = 0; i <= MAX; i++)
You should be using < MAX, *NOT* <= MAX.

SO now look at your code to reverse the elements, *EVEN AFTER* we change the <= to just < :
void array::reverse()
      for (short i = 0; i < MAX; i++)
         arr[i] = arr[(MAX  + 1)- i]; 
Let's "unroll" the loop and see what you are *ACTUALLY* doing:
arr[0] = arr[(5+1)-0] ==>> arr[0] = arr[6]
arr[1] = arr[(5+1)-1] ==>> arr[1] = arr[5]
arr[2] = arr[(5+1)-2] ==>> arr[2] = arr[4]
arr[3] = arr[(5+1)-3] ==>> arr[3] = arr[3]
arr[4] = arr[(5+1)-4] ==>> arr[4] = arr[2]

You *SHOULD* have been using
         arr[i] = arr[(MAX  - 1)- i]; // -1, *NOT* +1
But that's *STILL* not enough!

Let's make an example array:
arr[0] = 777
arr[1] = 222
arr[2] = 444
arr[3] = 888
arr[4] = 333
With YOUR code, even after my -1 adjustment, you would be doing:
arr[0] = arr[(5-1)-0] ==>> arr[0] = arr[4], so arr[0] is now 333
arr[1] = arr[(5-1)-1] ==>> arr[1] = arr[3], so arr[1] is now 888
arr[2] = arr[(5-1)-2] ==>> arr[2] = arr[2], so arr[2] is still 444
 arr[3] = arr[(5-1)-3] ==>> arr[3] = arr[1], so arr[3] is now 888!  got the NEW value of arr[1]!
 arr[4] = arr[(5-1)-4] ==>> arr[4] = arr[0], so arr[4] is now 333!  got the NEW value of arr[0]!
So you can see that this is complete mistake! You can *NOT* swap an array like that, *AT ALL*.

I'm sure this is homework for some class, and we don't do homework. (Or at least I won't.) We WILL help you when you run into trouble, as I have just done.

But now it is time for you to go put on your thinking cap and figure out the *RIGHT* way to swap an array.


p.s.: Weren't you suspicious when you couldn't even get your populate( ) function to work??? Didn't it give you an error when you tried to put the 6th value into your 5 element array? Or are you possibly not running this with a debugger and you just got an undiagnosed crash?
Reply With Quote
The Following User Says Thank You to Old Pedant For This Useful Post:
code_lover (February 25th, 2009)