One of the most
common operations performed on arrays is to swap two elements. As an example, consider our array numbers
from before and suppose we’d like to swap the first with the last element. numbers (before the swap)
0 1 2 3 4 numbers (after the swap)
0 1 2 3 4 Swapping requires us to create a temporary variable to save one of the
elements to be swapped, numbers[0] and numbers[4] (let’s save numbers[0]).
The value of numbers[4] is then assigned to numbers[0].
And finally, we copy the value of temp containing the saved value of numbers[0] to numbers[4].
Diagrammatically, this is what we’re trying to accomplish:
temp In code, this would
translate to: int temp = numbers[0]; numbers[0] = numbers[4]; numbers[4] = temp; |