JAVA program to reverse the elements of an array

JAVA program to reverse the elements of an array

This JAVA program is to reverse the elements of an array.

For example, if an array a consists of elements a={3,4,5} , then on reversing these elements we would get a={5,4,3}.

 Logic

We use a single for loop which will begin with 0, and start by storing the value of the last element in the initial position(index 0) and so on.

Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 3

Let us take elements for array a={1,2,3}.

1st iteration for(i=0;i<n;i++) i.e. for(i=0;0<3;i++)

reverse[i]=a[n-i-1]  i.e.  reverse[0]=a[3-0-1]   i.e.  reverse[0]=a[2]   i.e.  reverse[0]=3

2nd iteration for(i=1;i<n;i++) i.e. for(i=1;1<3;i++)

reverse[i]=a[n-i-1]  i.e.  reverse[1]=a[3-1-1]   i.e.  reverse[1]=a[1]   i.e.  reverse[1]=2

3rd iteration for(i=2;i<n;i++) i.e. for(i=2;2<3;i++)

reverse[i]=a[n-i-1]  i.e.  reverse[2]=a[3-2-1]   i.e.  reverse[2]=a[0]   i.e.  reverse[2]=1

Hence we have reversed the elements of an array and our final output is a={3,2,1}.

Program

import java.util.*;

class arr9
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		
	        int i,n;
		
		System.out.println("Enter the number of elements:") ;
 		n = sc.nextInt();
		int[] a = new int[n];
		int[] reverse = new int[n];
 
    		System.out.println("Enter the elements") ;
    		for(i=0;i<n;i++)
    		{ 
        		a[i] = sc.nextInt();
    		}
		
		for(i=0;i<n;i++)
    		{
			reverse[i] = a[n-i-1];
    		}
    		System.out.println("Elements in reverse order are");
    		for(i=0;i<n;i++)
    		{
        		System.out.print(reverse[i]+" ") ;
    		}
	}	
}

Output

Share Me!