In this tutorial you will learn about the Java Program to reverse an array and its application with practical example.
Java Program to Reverse an Array.
In this tutorial, we will learn to create a Java program that will reverse an Array Using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
Reversing an Array:-
In this program, First, we will first take the size of the array from the user. Then we will take the elements of the array from the user. Then we will copy elements of the array. After that, we will reverse the array using the for-loop. Then we will print the reverse of the original array to the user.
With the help of this program, we can be reverse an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.*; class ReversalArray { //Body of the main funciton. public static void main(String[] args) { //Declaring the required varaibles for the program. int size, res,i,j=0; //i,j = it will hold the integer value for the loops. Scanner s = new Scanner(System.in); //Taking the size of the array System.out.print("Enter number of elements in the array:"); size = s.nextInt(); int array[] = new int[size]; int rev[] = new int[size]; //Taking the elements of the array System.out.println("Enter "+size+" elements "); for( i=0; i < size; i++) { array[i] = s.nextInt(); } //Reversing the array for the user. System.out.println("Reverse of an array is :"); for( i=size;i>0 ; i--,j++) { rev[j] = array[i-1]; //Printing the reversal of the array to the user. System.out.println(rev[j]); } } } |
Output:-
In the above program, we have first initialized the required variable.
- array[] = it will hold the integer value.
- i = it will hold the integer value.
- j = it will hold the integer value.
- size = it will hold the integer value.
Taking the size of the array and the elements.
Program Code to Reverse an Array.
Printing reversed array to the user.