Arrays
Reverse an array in place by swapping pairs from opposite ends.
Complete program
#include <stdio.h>
int main(void) {
int values[] = {1, 2, 3, 4, 5};
size_t count = sizeof values / sizeof values[0];
for (size_t i = 0; i < count / 2; ++i) {
int temporary = values[i];
values[i] = values[count - 1 - i];
values[count - 1 - i] = temporary;
}
for (size_t i = 0; i < count; ++i)
printf("%d%s", values[i], i + 1 == count ? "\n" : " ");
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Every pair needs exactly one swap. Iterating only to count / 2 prevents swapping elements back to their original positions. For an odd count, the middle element stays in place.
A temporary variable prevents losing the left-hand value when it is replaced. Test arrays with one, two, and four elements, then compare this algorithm with printing the original array backwards without changing it.
Expected output
5 4 3 2 1Concepts to practice
- In-place algorithms
- Symmetric indexes
- Swapping
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.