Reverse of an array using java

Reverse of an array using java

Here we will learn about how we can reverse the array.

For reversing the array we just need to apply a backward loop and we start storing from the last element of the array first into the first index of the second array.

Reversing the array in java can be done very easily.

Example

input            4 5 1 7 4 6 0 1 5

Output         5 1 0 6 4 7 1 5 4
reverse

Working

Step 1. Initialize two arrays.

Step 2. Declare the scanner class for taking input.

Step 3. take first array size from the user.

Step 4. Take an element of the array from the user.

Step 5. The print sum from calling the sum function.

Step 6. Initialise backwards loop for storing the last element of the array into the second array first element.

Step 7. Print reverse array

Step 8. Stop.

Java program to reverse the array

import java.util.Scanner;
public class Main
{
public static void main(String[] args) 
{
int j=0;
//initialise first array
int[] arr=new int[40];
//initialise second array for store reverse array
int[] rev=new int[40];
//declare scanner class
Scanner sc=new Scanner(System.in);
//take input of size from the user
System.out.println("enter size");
int size=sc.nextInt();
//take element of array1 from user
System.out.println("enter element");
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
//here we are stroring last element of array in the reverse array
for(int i=size-1;i>=0;i--)
{
rev[j]=arr[i];
j++;
}

System.out.println("the reverse array");
//print reverse array
for(int i=0;i<size;i++)
System.out.print(rev[i]+" ");
}
}

Output

enter size 
3
enter element
1
2
3
the reverse array
3 2 1

Please Login/Signup to comment