Java programs to display array elements in reverse order have been shown here. Both of the iterative and recursive approaches have been covered. The algorithm, pseudocode and time complexity of the programs have also been given.
Example:
Given array A[] = {5, 10, 15, 25, 30}
Elements of A[] in reverse order = {30, 25, 15, 10, 5}
Page content(s):
1. Algorithm to display array elements in reverse order
1. Take input of an array $A[~]$ and the size $n$
2. Set $i = n - 1$
3. For each $i$ from $n - 1$ to $0$, dislay $A[i]$
2. Pseudocode to display array elements in reverse order
Input: An array $A[~]$ and size of array $n$
Output: Array elements in reverse order.
1. Procedure reverse($A[~]$, $n$):
2.
3.
4. End Procedure
3. Time complexity to display array elements in reverse order
Time Complexity: O(n)
Here $n$ is the number of elements in the array.
4. Program & output to display array elements in reverse order
4.1. Java Program & output to display array elements in reverse order using iterative approach
/*************************************** alphabetacoder.com Java program to print elements of array in reverse order using iteration ****************************************/ class Main { public static void main(String args[]) { // declare an array int[] arr = {10, 20, 30, 40, 50, 60, 70, 80}; // declare variables int i, length; // calculate size of array length = arr.length; // display the array System.out.print("Original array: "); for (i = 0; i < length; i++) System.out.print(arr[i] + " "); // display array elements in reverse order System.out.print("\nReverse array : "); for (i = length - 1; i >= 0; i--) System.out.print(arr[i] + " "); } }
Output
Original array: 10 20 30 40 50 60 70 80
Reverse array : 80 70 60 50 40 30 20 10
4.2. Java Program to display array elements in reverse order using recursion
/*************************************** alphabetacoder.com Java program to print elements of array in reverse order using recursion ****************************************/ class Main { // display elements of array in reverse // order function takes an array arr and // an index i as arguments public static void reverse(int arr[], int i) { // exit condition of recursive call if (i < 0) return; // print current element System.out.print(arr[i] + " "); // call function reverse(arr, i - 1); } public static void main(String args[]) { // declare an array int[] arr = {10, 20, 30, 40, 50, 60, 70, 80}; // declare variables int i, length; // calculate size of array length = arr.length; // display the array System.out.print("Original array: "); for (i = 0; i < length; i++) System.out.print(arr[i] + " "); // display array elements in reverse // order using recursive function reverse() // pass array arr and last index of array as // arguments System.out.print("\nReverse array : "); reverse(arr, length - 1); } }