Reverse an Array in JAVA

Reversing an Array

In this article we’ll learn a JAVA program using which we can Reverse the position of the elements in an array. For Ex. If the input array is Arr[]= {1, 2, 3, 4, 5, 6, 7, 8,  9}  then the output array will be Arr[]= {9, 8, 7, 6, 5, 4, 3, 2, 1,}.

Reverse an Array

Explanation

In this Approach of solving the problem above we’ll interchange or swap the elements at the first position with the element at the last position, the element at the second position will be swapped by the element at the second last position So on and So forth.

Algorithm

  • reverse( array, length of array)
  • temp=0
  • FOR i=0 to i= length/2
  • temp = array[i]
  • array[i] = array[length-i-1]
  • array[length-i-1] = temp
  • FOR end
import java.util.*;
class Main { 
    static void reverse(int a[], int n) 
    { 
        int temp=0; 
        for (int i = 0; i < n / 2; i++) { 
            temp = a[i]; 
            a[i] = a[n - i - 1]; 
            a[n - i - 1] = temp; 
        } 
        System.out.println(" \n Reversed array is:"); 
        for (int j = 0; j < n; j++) { 
            System.out.println(a[j]); 
        } 
    } 
  
    public static void main(String[] args) 
    { 
        Scanner s= new Scanner(System.in); 
        System.out.println("Enter length of the array");
        int l=s.nextInt(); 
        System.out.println("Enter the elements of the array"); 
        int[] arr= new int[l];
        for(int i=0; i<l; i++)
            arr[i]=s.nextInt();
        reverse(arr, l); 
    } 
}
Enter length of the array
6
Enter the elements of the array
1
2
3
4
5
6

Reversed array is:
6
5
4
3
2
1