Java Program to Reverse an Array - The Coding Shala
Home >> Java Programs >> Reverse an Array
Other Posts You May Like
In this post, we will learn how to Reverse an Array in Java.
Java Program to Reverse an Array
You have given an Array, Write a Java Program to Reverse the given array.
Example 1:
Input: arr = {1,2,3,4,5}
Output: arr = {5,4,3,2,1}
Approach 1
We can use an extra array to store the elements in reverse order then copy all the elements into the original array.
The alternate way is we can swap elements in the same array. For example, swap the first element with the last element, swap the second element with the second last element and continue.
Java Program:
// Java program to Reverse an Array public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("Before Reverse array is: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); // swap ith and length-ith element for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - i - 1]; arr[arr.length - i - 1] = temp; } // print array System.out.println("Reversed Array is: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Output:
Before Reverse array is: 1 2 3 4 5 Reversed Array is: 5 4 3 2 1
- Java Program to Print the Sum of all the elements of the array
- Java Program to Sort an Array in Ascending Order
- Java Program to Sort an Array in Descending Order
- Java Program to Count Negative Numbers in Sorted Matrix
- Java Program to Reverse a String
Comments
Post a Comment