JAVA program to reverse elements of array using same array

JAVA program to reverse the elements of an array using the same array

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

For example, if an array a consists of elements a={7,8,9} , then on reversing these elements we would get a={9,8,7}.

 Logic

We use a while loop which and then perform swap operation with last and first 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}.

i=0;

j=n-1  i.e. j=3-1 i.e. j=2

1st iteration while(i<j)  i.e. while(0<2)

temp=a[i];  i.e. temp=a[0]  i.e. temp=1

a[i]=a[j];  i.e. a[0]=a[2]   i.e. a[0]=3

a[j]=temp;  i.e.  a[2]=1

i++;  i.e. i=0+1  i.e. i=1;

j–;  i.e. j=2-1  j=1

As i(1) is not less than j(1) we come out of the while loop.

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

Program

import java.util.*;

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

    		System.out.println("Elements in reverse order are");
    		for(i=0;i<n;i++)
    		{
        		System.out.print(a[i]+" ") ;
    		}
	}	
}

Output

Share Me!