Swapping elements in an array
What you'll learn: How to exchange the values of two specific positions within an array using a temporary variable.
The musical chairs problem
Imagine you have two friends sitting in chairs: Alice is in Chair 0 and Bob is in Chair 1. You want them to switch seats. If Alice tries to sit in Bob’s chair while he is still there, they’ll crash! To swap them safely, you need a third, empty "temporary" chair.
Alice moves to the temporary chair, Bob moves to Chair 0, and then Alice moves from the temporary chair into Chair 1. In C programming, we follow this exact three-step logic to swap values in an array.
The logic of the "Temp" variable
Computers cannot simply "flip" two memory locations at once. If you write array[0] = array[1], the original value in array[0] is overwritten and lost forever.
To prevent this, we use a temporary variable (often called temp) to hold the data from the first spot while we move the second piece of data into it.
Implementing a swap in C
Here is how you would swap the first and second elements of an integer array:
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40};
// Step 1: Save the value of the first element into a temporary variable
int temp = numbers[0];
// Step 2: Overwrite the first element with the value of the second element
numbers[0] = numbers[1];
// Step 3: Move the saved value from 'temp' into the second element
numbers[1] = temp;
// The array is now {20, 10, 30, 40}
printf("Index 0: %d, Index 1: %d", numbers[0], numbers[1]);
return 0;
}
Why this matters
Swapping is the fundamental building block for almost every sorting algorithm. Whether you are arranging a list of names alphabetically or sorting high scores from largest to smallest, you are essentially repeating this "three-step dance" over and over again until the elements are in the correct order.
Key takeaway
To swap two array elements, you must use a temporary variable to hold one value so it isn't lost when you overwrite it.