In this tutorial, We will learn writing Java program to create an Array and return the elements in Reverse Order.
Our program will first take the input of array size and then the elements of the array. And return the reverse of the input array.
For Example
Case 1: If the user inputs 4 as array (list) size and the array (list) elements as 1,2,3,4.
The output should be 4,3,2,1.
Case 2: If the user inputs 5 as array (list) size and the array (list) elements as 9,8,7,6,5.
The output should be 5,6,7,8,9.
Program 1: Java Program to Print Array in Reverse Order using For Loop
import java.util.*;
public class Main {
public static void main(String[] args) {
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of an array: ");
n=sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++)
{
System.out.print("Please give value for index "+i+" : ");
arr[i]=sc.nextInt();
}
System.out.println("Our original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array after reverse: ");
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
Output
Enter the size of an array: 5
Please give value for index 0 : 4
Please give value for index 1 : 3
Please give value for index 2 : 2
Please give value for index 3 : 1
Please give value for index 4 : 3
Our original array:
4 3 2 1 3
Array after reverse:
3 1 2 3 4
Explanation
The input array size is 5, so the ‘for loop’ will executes the body 5 times taking input from the users as the elements of the array, which is {4,3,2,1,3}. The program returned the reverse of the input array i.e. {3,1,2,3,4}.
Program 2: Java Program to Print Array in Reverse Order using While Loop
import java.util.*;
public class Main
{
public static void main(String[] args) {
int startIndex,lastIndex;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
int reverse[] = new int[size];
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
startIndex = 0;
lastIndex = size - 1;
while(lastIndex >= 0)
{
reverse[startIndex] = arr[lastIndex];
startIndex++;
lastIndex--;
}
System.out.println("Array After Reversing :");
for(int i=0; i<size; i++)
{
System.out.print(reverse[i]);
}
}
}
Output
Enter the size of array: 5
Please give value for index 0 : 6
Please give value for index 1 : 3
Please give value for index 2 : 7
Please give value for index 3 : 2
Please give value for index 4 : 1
Array After Reversing :
12736
Explanation
The input array size is 5, so the ‘for loop’ will executes the body 5 times taking input from the users as the elements of the array, which is {6,3,7,2,1}. The program returned the reverse of the input array i.e. {1,2,7,3,6}.