1. Introduction
Reversing an array is a common operation in programming. It involves rearranging the elements of an array in the opposite order. This post will guide you through a simple approach to reverse an array in Java.
2. Program Steps
1. Initialize an array originalArray.
2. Create another array reversedArray of the same length as originalArray.
3. Iterate over originalArray and fill reversedArray with elements in the reverse order.
4. Display the reversedArray.
3. Code Program
public class ReverseArray {
public static void main(String[] args) {
// Step 1: Initialize an array originalArray
int[] originalArray = {1, 2, 3, 4, 5};
// Step 2: Create another array reversedArray of the same length as originalArray
int[] reversedArray = new int[originalArray.length];
// Step 3: Iterate over originalArray and fill reversedArray with elements in reverse order
for (int i = 0; i < originalArray.length; i++) {
reversedArray[i] = originalArray[originalArray.length - 1 - i];
}
// Step 4: Display the reversedArray
System.out.print("Reversed Array: ");
for (int elem : reversedArray) {
System.out.print(elem + " ");
}
}
}
Output:
Reversed Array: 5 4 3 2 1
4. Step By Step Explanation
In Step 1, we initialize an integer array named originalArray with some elements.
For Step 2, we create a new array called reversedArray that has the same length as originalArray.
During Step 3, we iterate over originalArray, and for each iteration, we place the current element in the corresponding reverse position in reversedArray. The position is calculated as originalArray.length – 1 – i.
Finally, in Step 4, we print out the reversedArray to display the reversed elements.