Prime

#### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

#### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# Java Program for reversing an array

## Reverse of an array

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

### Algorithm for reversing an array

• 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 the element of the array from the user.
• Step 5. 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 Code for reversing an 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
5
enter element
2
4
5
6
1
the reverse array
1 6 5 4 2
```

### One comment on “Java Program for reversing an array”

• Shubham

public class JavaApplication1
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
int n,s=0;
n = obj.nextInt();
int a[] = new int[n];
for(int i =0;i<n;i++)
{
a[i]=obj.nextInt();
}

for(int j=0;j<n/2;j++)
{
int x=a[j];
a[j]=a[n-1-j];
a[n-1-j]=x;
}
for(int k =0;k<n;k++)
{
System.out.print(a[k]);
}

}
}