Java Code Example: array in reverse order

This is a Java program that demonstrates how to reverse an array. Here’s a step by step explanation of the code:

  1. The program declares an array numbers with the values 1, 2, 3, 4, 5, 6, 7.
  2. In the first for loop, the program prints the elements of the numbers array.
  3. In the second for loop, the program prints the elements of the numbers array in reverse order. This is achieved by starting the loop counter i at numbers.length - 1 (the index of the last element in the array) and decrementing i in each iteration until it reaches 0.
public class ReverseArray {
	public static void main(String[] args) {
		int[] numbers = {1, 2, 3, 4, 5, 6, 7};
		int i = 0;

		// print array
		for (i = 0; i < numbers.length; i++) {
			System.out.print(numbers[i] + " ");
		}
		
		System.out.println();
		
		// print array in reverse order
		for (i = numbers.length - 1; i >= 0; i--) {
			System.out.print(numbers[i] + " ");
		}
	}
}
Output
1 2 3 4 5 6 7 
7 6 5 4 3 2 1