🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Reverse an Array in C
Reverse an array in C in place with two indices and a swap. Understand the comma operator, odd and even lengths and byte-order reversal for embedded work.
This lecture of our free C programming course teaches you how to reverse an array in C without allocating a second array. You will see every swap printed on screen.
We also connect the idea to a real firmware task, changing the byte order of a 32-bit value. All programs were compiled and run, and the output you see is the real output.
What You Will Learn
- The two-index swap method to reverse an array in place
- Why a temporary variable is required
- How the comma operator drives two loop variables
- What happens at the middle of odd and even length arrays
- Reversing a byte array to change endianness
Prerequisites
- Previous lectures of this arrays chapter
- Understanding of
forloops and array indexing - Basic idea of what a byte and a 32-bit word are
How to Reverse an Array in C: Swap From Both Ends
To reverse an array in C you do not need a second array. The trick is to put one finger on the first element and another on the last, swap the two values, then move both fingers toward the middle. When the fingers meet or cross, every pair has been swapped and the array is reversed in place. Only half of the elements ever need a swap: for N elements you perform N/2 swaps, rounded down.
Seven elements, three swaps
The Swap Needs a Temporary Variable
A swap must keep both values alive at the same time. If you write a[i] = a[j]; first, the old value of a[i] is gone forever, and the next line has nothing to copy back. A temporary variable holds one value while the other moves.
Three-step swap using tmp
Two Indices and the Comma Operator
The loop needs two counters that move in opposite directions. C lets you put two expressions in the initialization part and two in the update part of a for statement by separating them with the comma operator, which evaluates the left expression first and then the right one.
for (i = 0, j = LEN - 1; i < j; i++, j--) {
/* swap a[i] and a[j] */
}Read it as: start i at the first index and j at the last, continue while i is still left of j, and after each pass move i right and j left. Do not confuse this with the commas in a declaration like int i, j; or in function arguments; those are only separators, not the comma operator.
The same logic can be written with a while loop, and some programmers find it easier to read: set left = 0 and right = N - 1 before the loop, then inside the body swap and finally do left++ and right--. The compiler produces almost identical machine code for both forms, so choose the one your team finds clearer. What matters is that the two indices always move toward each other by exactly one step per pass, because that guarantees the loop ends after N/2 passes and never touches an element outside the array.
C Program to Reverse an Array in Place
The program below reverses seven numbers and prints the array after every swap, so you can watch the fingers move. The odd length is deliberate: it shows what happens to the middle element.
#include <stdio.h>
#define LEN 7
int main(void)
{
int a[LEN] = {11, 22, 33, 44, 55, 66, 77};
int i, j, tmp, k;
for (i = 0, j = LEN - 1; i < j; i++, j--) {
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
printf("swap a[%d] and a[%d] ->", i, j);
for (k = 0; k < LEN; k++) printf(" %d", a[k]);
printf("\n");
}
printf("final array :");
for (k = 0; k < LEN; k++) printf(" %d", a[k]);
printf("\nloop stopped with i=%d j=%d\n", i, j);
return 0;
}$ gcc -std=c17 -Wall -Wextra -o ep_arr_reverse ep_arr_reverse.c
$ ./ep_arr_reverse
swap a[0] and a[6] -> 77 22 33 44 55 66 11
swap a[1] and a[5] -> 77 66 33 44 55 22 11
swap a[2] and a[4] -> 77 66 55 44 33 22 11
final array : 77 66 55 44 33 22 11
loop stopped with i=3 j=3After three swaps the array is fully reversed. Look at the last line: the loop stopped with i=3 and j=3. Both indices point at the middle element, and swapping an element with itself would achieve nothing, so the condition i < j correctly stops there.
Even length versus odd length
| Length N | Swaps performed | Index pairs | Loop stops with | Untouched element |
|---|---|---|---|---|
| 6 | 3 | (0,5) (1,4) (2,3) | i=3, j=2 | none |
| 7 | 3 | (0,6) (1,5) (2,4) | i=3, j=3 | index 3 |
Embedded Use Case: Reversing Bytes for Endianness
Why does a firmware student care about reversing an array? Because bytes arrive in a buffer in one order and a protocol may want the opposite. A sensor may send a 32-bit value most-significant byte first, while your little-endian MCU stores it least-significant byte first. Reversing the four-byte array converts between the two. The next program does exactly that using a uint8_t array.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main(void)
{
uint32_t word = 0x12345678u;
uint8_t raw[4];
int i, j;
memcpy(raw, &word, sizeof word);
printf("before : 0x%08X, bytes in memory:", (unsigned)word);
for (i = 0; i < 4; i++) printf(" %02X", raw[i]);
printf("\n");
for (i = 0, j = 3; i < j; i++, j--) {
uint8_t t = raw[i];
raw[i] = raw[j];
raw[j] = t;
}
memcpy(&word, raw, sizeof word);
printf("after : 0x%08X, bytes in memory:", (unsigned)word);
for (i = 0; i < 4; i++) printf(" %02X", raw[i]);
printf("\n");
return 0;
}$ gcc -std=c17 -Wall -Wextra -o ep_byte_swap ep_byte_swap.c
$ ./ep_byte_swap
before : 0x12345678, bytes in memory: 78 56 34 12
after : 0x78563412, bytes in memory: 12 34 56 78The first line shows the bytes the way a little-endian PC stores 0x12345678: 78 56 34 12. After the reversal loop the bytes are 12 34 56 78 and the 32-bit word reads back as 0x78563412. On a big-endian machine the first line would differ, which is a good reminder that byte order is a property of the machine, not of the number.
htonl(), ntohl() or the compiler’s __builtin_bswap32(). They are tested and often compile to one instruction. Write the loop yourself to learn the idea, then use the library in a product.Other Real-World Applications
- Reversing a string or a digit buffer, for example when you build a number backwards and must print it forwards.
- Converting a most-significant-bit-first bit pattern into least-significant-bit-first order for a shift register.
- Playing a recorded sample buffer backwards in a simple audio effect.
- Turning a ring buffer snapshot into newest-first order for a display.
Common Mistakes When You Reverse an Array in C
| Mistake | What you see | Fix |
|---|---|---|
Loop runs to i < N instead of stopping at the middle | The array comes out unchanged because every pair is swapped twice | Stop when i < j fails |
Starting j at N | Reads and writes one element past the array | Start at N - 1 |
Swapping without tmp | Two equal values appear, one value lost | Always save one value first |
Using an unsigned length and computing N - 1 when N is 0 | The result wraps to a huge number, memory corruption | Return early if the length is less than 2 |
Reversing a const array | Compile error or a crash on flash memory | Copy it into a RAM array first |
Best Practices, Performance and Safety
- Reverse in place when RAM is tight. A second array costs N extra elements, while the swap method needs one temporary variable.
- Performance: time is O(N) and extra memory is O(1). Only N/2 swaps happen, so it is cheap even on an 8-bit MCU.
- Guard against lengths of 0 and 1. There is nothing to do, and an unsigned subtraction can bite you.
- Security: if the length or the data comes from outside the device, validate the length against the buffer size before reversing. A swap loop with a bad bound is a write primitive for an attacker.
- Name the two indices
leftandrightin production code; short names likeiandjare fine for teaching.
Summary and Key Takeaways
- Reverse in place by swapping a[i] with a[j] while i is less than j.
- A swap needs a temporary variable.
- The comma operator lets one
forloop drive two indices. - Odd-length arrays keep their middle element where it is.
- Reversing a byte array is how you change endianness, but prefer library functions in real products.
Conclusion
You can now reverse an array in C without any extra memory, explain why only half the elements need a swap, and connect the idea to real byte-order problems in firmware. It is a favourite question in written tests and interviews, and it is also the first step of the decimal-to-binary conversion in the next lecture of this free embedded C course.
Topics Covered in This Free Embedded C Lecture
Frequently Asked Questions
How do I reverse an array in C without another array?
Use two indices, one at each end. Swap the two elements, move the left index up and the right index down, and stop when they meet or cross.
Why does the loop condition use i < j?
When i reaches j both point at the same middle element, or they have crossed. Swapping further would undo earlier swaps.
How many swaps are needed for N elements?
N divided by 2, rounded down. A seven element array needs three swaps and the middle element stays put.
What is the comma operator doing in the for loop?
It lets you write two expressions in one slot, so i++, j-- updates both indices after every pass, evaluated left to right.
Is reversing bytes the same as converting endianness?
For a fixed-size value stored as an array of bytes, yes. Reversing the byte order converts big-endian to little-endian and back.
Can I use this on a const array?
No, a const array cannot be modified. Copy it into a normal RAM array and reverse the copy.
Continue the Free C Tutorial
Next up: converting a decimal number to binary using an array. It uses the reversal idea you just learned.

2 Comments