Course contentsShow
← Java
Lesson 251 of 2,8706. ArraysFree lesson

Iterating Arrays in Reverse Order

Master reverse iteration patterns using decreasing index variables in for loops.

Iterating Arrays in Reverse Order

What you'll learn: You'll discover how to walk through an array from the last element to the first using a reverse-counting for loop.

The Core Idea

So far, you've learned to iterate arrays from start to finish (index 0 to length - 1). But sometimes you need to process elements in the opposite direction—starting at the last element and moving backward to the first. This is called reverse iteration.

Think of it like reading a book backward: instead of starting at page 1 and incrementing, you start at the last page and count down.

How It Works

The key is using a traditional for loop with a decreasing index variable:

int[] numbers = {10, 20, 30, 40, 50};

// Reverse iteration: start at last index, decrease until reaching 0
for (int i = numbers.length - 1; i >= 0; i--) {
    System.out.println(numbers[i]);
}

Output:

50
40
30
20
10

Breaking Down the Pattern

  1. Initialization: i = numbers.length - 1 — Start at the last valid index
  2. Condition: i >= 0 — Continue while index is valid (don't go negative!)
  3. Update: i-- — Decrease the index each iteration instead of increasing

Notice you can't use an enhanced for loop here—it only goes forward. Reverse iteration requires explicit index control.

Common Use Case

Imagine displaying search results "newest first" or processing undo operations in reverse chronological order:

String[] actions = {"Open file", "Edit text", "Save", "Close"};

// Undo in reverse order
for (int i = actions.length - 1; i >= 0; i--) {
    System.out.println("Undoing: " + actions[i]);
}

Key Takeaway: Reverse array iteration uses a for loop starting at length - 1, continuing while >= 0, and decrementing the index with i--.