What is Reverse an Array in C- Embedded C Programming Course Online

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Arrays · Lecture 8

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.

8
Arrays chapter
12 min
Read and practise
100%
Free forever

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 for loops 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

start11223344556677
pairsswap 11 and 77swap 22 and 66swap 33 and 55
middle44 has no partner and stays in the centre
end77665544332211

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

step 1tmp = a[i]saves the left value
step 2a[i] = a[j]left slot now has the right value
step 3a[j] = tmpright slot gets the saved value

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=3

After 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 NSwaps performedIndex pairsLoop stops withUntouched element
63(0,5) (1,4) (2,3)i=3, j=2none
73(0,6) (1,5) (2,4)i=3, j=3index 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 78

The 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.

Production tip: for real code use 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

MistakeWhat you seeFix
Loop runs to i < N instead of stopping at the middleThe array comes out unchanged because every pair is swapped twiceStop when i < j fails
Starting j at NReads and writes one element past the arrayStart at N - 1
Swapping without tmpTwo equal values appear, one value lostAlways save one value first
Using an unsigned length and computing N - 1 when N is 0The result wraps to a huge number, memory corruptionReturn early if the length is less than 2
Reversing a const arrayCompile error or a crash on flash memoryCopy 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 left and right in production code; short names like i and j are 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 for loop 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

free c programming coursefree c tutorialc programming for embedded systemsembedded c programmingfree embedded c coursec arrays for beginnersreverse an array in Cswap array elementsendianness byte swap

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 &lt; 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.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *