Just as it’s possible to rotate elements in an array, shuffling them all up a notch and moving the first element to the end, it’s also possible to flip an array, reversing the order of its elements.
For example, you start with this array:
{ 1, 2, 3, 4, 5, 6, 7, 8 }
After the operation, the array’s values are:
{ 8, 7, 6, 5, 4, 3, 2, 1 }
As shown in last week’s Lesson, it’s possible to perform this operation without requiring a second array. Here’s how I do it:
2025_03_01-Lesson.c
#include <stdio.h> int main() { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int size,x,save; /* obtain array size */ size = sizeof(a)/sizeof(a[0]); /* output the array */ for( x=0; x<size; x++ ) printf(" %d",a[x]); putchar('\n'); /* reverse the elements */ for( x=0; x<(size/2); x++ ) { save = a[x]; a[x] = a[size-x-1]; a[size-x-1] = save; } /* output the array */ for( x=0; x<size; x++ ) printf(" %d",a[x]); putchar('\n'); return 0; }
After the array is output, a for loop reverses the elements. Variable save
holds the value of the first element, which is then replaced with the value of the last element. Then the last element is set to the value of int variable save
:
for( x=0; x<(size/2); x++ )
{
save = a[x];
a[x] = a[size-x-1];
a[size-x-1] = save;
}
This operation repeats as variable x
increments to half the size of the array. A final for loop outputs the results:
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
This code is designed to handle an array of any size, which is why the statement size = sizeof(a)/sizeof(a[0]);
is used to obtain the array’s size. But what about an array with an odd number of elements?
I modified the value of a[]
to add three more elements: 9, 10, and 11. Here’s the program’s updated output:
1 2 3 4 5 6 7 8 9 10 11
11 10 9 8 7 6 5 4 3 2 1
Because the size/2
expression works with integers, the “half” value is rounded down, which means the middle element — no matter what the array size — isn’t swapped. It doesn’t need to be!
This type of manipulation is demonstrated with an integer array. In next week’s Lesson I cover messing with an array of strings.
Didn’t you write about this before, ages ago? I have some vague memory (all my memories are vague!) of commenting firstly that you can use the XOR swap thing, and also that if you need the data reversed then it’s often easier just to iterate backwards.
OMG. Yup: https://c-for-dummies.com/blog/?p=2046