It helps if you do the operation on a whiteboard. Draw a square to represent the start element of the array. Draw another square to represent the end element of the array. Inside the squares, write the value held by that element. It would look something like this:
Then do the operations as the computer would do them. What happens when you assign the value of the end element to the start element? What happened to the old value of the start element? Then, what happens now when you assign the value of the start element to the end element?
Try it again, only this time, add another box for temp. What happened?
I'm sorry I still don't get why you need a temporary place holder for the array. I know by setting arr[start] = arr[end], or arr[3] = arr[8] doesn't make any logical sense. But isn't this saying the same thing when you have:
I meant that 3 and 8 were the values of the start and end array elements respectively, not index values. Don't think of index values at all, just think of them as single-item capacity holders of things. If one element can hold only one thing at a time then you can't just simply assign a new value without first saving the old value. The temp variable is the holder of that saved old value.
Timothy Han wrote:I'm sorry I still don't get why you need a temporary place holder for the array.
There are actually a few ways to swap two variables' values without a temporary variable. Most of the time, it is not done, because it may be confusing to understand (and developers tend to avoid confusing code). I am assuming that you are asking this question, because you know of a way to do it? If so, can you just show us -- and we can either confirm or deny whether it will work?