Reverse the array - Java Program

Q. Write a program to reverse the elements of an array.

Answer:

In this example, we reverse the given array element. Add the array element to using of Scanner class. We create a reverse() method, which performs the reverse operation.  

Reverse.java

import java.util.*;
class Reverse
{
    public static void reverse(int[] arr)
    {
        for(int i=0;i<arr.length/2;i++)
        {
            int temp=arr[i];
            arr[i]=arr[(arr.length-1)-i];
            arr[(arr.length-1)-i]=temp;
        }
    }
    public static void main(String args[])
    {
        Scanner scn = new Scanner(System.in);
        System.out.println("Enter the number of elements: ");
        int n=scn.nextInt();
        int arr[]=new int[n];

        System.out.println("Enter the elements into the array");
        for(int i=0;i<n;i++)
        {
            arr[i]=scn.nextInt();
        }

        reverse(arr);
        System.out.println("After reversing the array:");
        for(int i=0;i<n;i++)
        {
            System.out.printf("a[%d]=%d\n",i,arr[i]);
        }
    }   
}


Output:

reverse array