Course contentsShow
← C
Lesson 401 of 1,2196. Arrays and StringsFree lesson

Reverse traversal of an array

Reverse traversal of an array

What you'll learn: How to process array elements in backwards order by carefully managing your loop index.

Starting at the finish line

Normally, when we iterate through an array, we start at index 0 and move forward. However, many programming problems—like reversing a string or checking the last few entries in a log—require us to start at the end and walk toward the beginning.

Think of an array like a staircase. Forward traversal is climbing up from the ground floor. Reverse traversal is standing at the top and stepping down until you reach the bottom. To do this successfully in C, you have to be very specific about where you start and where you stop to avoid "falling off" the ends of the array.

Setting the boundaries

To walk backwards, we need to adjust the three parts of our for loop:

  1. The Starting Point: If an array has N elements, the last valid index is always N - 1 (because we start counting at 0).
  2. The Condition: We want to keep moving as long as our index is greater than or equal to 0.
  3. The Step: Instead of incrementing (i++), we decrement (i--) to move one slot to the left each time.

Code Example: The Countdown

Here is how you would print an array of numbers in reverse order:

#include <stdio.h>

int main() {
    int countdown[] = {1, 2, 3, 4, 5};
    int size = 5;

    printf("Ignition sequence: ");

    // Start at index 4 (size - 1), stop after index 0
    for (int i = size - 1; i >= 0; i--) {
        printf("%d... ", countdown[i]);
    }

    printf("Liftoff!\n");

    return 0;
}

Watch your step!

The most common mistake in reverse traversal is the "Off-by-One" error. If you accidentally start at i = size, you are pointing at a memory location just outside the array, which contains "garbage" data or could cause your program to crash. Similarly, ensure your condition is i >= 0. If you use i > 0, you will stop early and skip the very first element (the one at index 0).

Key takeaway

To traverse an array backwards, initialize your loop at size - 1, decrement the index, and continue until you have processed index 0.