Reversing an array.
Here’s a Java program that reverses an array:
import java.util.Arrays; public class ArrayReversal { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; System.out.println("Original Array: " + Arrays.toString(array)); reverseArray(array); System.out.println("Reversed Array: " + Arrays.toString(array)); } public static void reverseArray(int[] arr) { int start = 0; int end = arr.length - 1; while (start < end) { // Swap elements at start and end positions int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; // Move the pointers towards the center start++; end--; } } }
This program defines a method called `reverseArray()` that takes an integer array as input and reverses it by swapping elements from the start and end positions until the pointers meet in the middle. The `main()` method demonstrates the usage of the `reverseArray()` method by creating an array, reversing it, and then printing both the original and reversed arrays.
When you run the program, it will output:
Original Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]
The original array `[1, 2, 3, 4, 5]` gets reversed to `[5, 4, 3, 2, 1]`.
No comments yet! You be the first to comment.