View Single Post
 Old Pedant Friend of Wrox Join Date: Jun 2008 Location: Snohomish, WA, USA Posts: 1,649 Thanks: 3 Thanked 141 Times in 140 Posts Code:
```const int MAX = 5;
...
int arr[MAX];```
So how many ELEMENTS will be IN that array???

Yes, 5.

But HOW are they NUMBERED???

Code:
```arr
arr
arr
arr
arr```
Yes, zero through 4. Only.

So even your display( ) function is wrong:
Code:
```void array::display()
{
for (short i = 0; i <= MAX; i++)
cout<<arr[i]<<endl;
}```
You should be using < MAX, *NOT* <= MAX.

SO now look at your code to reverse the elements, *EVEN AFTER* we change the <= to just < :
Code:
```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:
Code:
```arr = arr[(5+1)-0] ==>> arr = arr
arr = arr[(5+1)-1] ==>> arr = arr
arr = arr[(5+1)-2] ==>> arr = arr
arr = arr[(5+1)-3] ==>> arr = arr
arr = arr[(5+1)-4] ==>> arr = arr```
OOPS!!!

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

Let's make an example array:
Code:
```arr = 777
arr = 222
arr = 444
arr = 888
arr = 333```
With YOUR code, even after my -1 adjustment, you would be doing:
Code:
```arr = arr[(5-1)-0] ==>> arr = arr, so arr is now 333
arr = arr[(5-1)-1] ==>> arr = arr, so arr is now 888
arr = arr[(5-1)-2] ==>> arr = arr, so arr is still 444
arr = arr[(5-1)-3] ==>> arr = arr, so arr is now 888!  got the NEW value of arr!
arr = arr[(5-1)-4] ==>> arr = arr, so arr is now 333!  got the NEW value of arr!```
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?
 The Following User Says Thank You to Old Pedant For This Useful Post: code_lover (February 25th, 2009)