JAVA program to shift elements of an array in the left direction

 

JAVA program to shift elements of a single dimensional array in the left direction by one position

This JAVA program is to shift the elements of a single dimensional array in the left direction by one position.

For example, if an array a consists of elements a={9,10,11}, then on shifting these elements towards the left direction we would get a={11,10,9}.

 Logic

We store the first element in the temp variable and then put it in the last position i.e. a[n-1] and the remaining elements we shift it towards the left by one position by storing the element in the current position to the previous position.

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}.

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

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

a[i]=a[i+1];  i.e. a[0]=a[0+1] i.e. a[0]=a[1] i.e. a[0]=2

2nd iteration  for(i=1;1<2;i++)

a[i]=a[i+1];  i.e. a[1]=a[1+1] i.e. a[1]=a[2] i.e. a[1]=3

As i(2) is not less than 2 we come out of the for loop.

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

Hence we have shifted the elements of an array in the left direction by one position and our final output is a={2,3,1}.

Program

import java.util.*;

class arr12
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		
	        int i,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();
    		}
		
	    	System.out.println("Original array");
    		for(i=0;i<n;i++)
    		{
        		System.out.print(a[i]+" ");
    		}
 
    		/* shifting array elements */
    		temp=a[0];
    		for(i=0;i<n-1;i++)
    		{
       	 		a[i]=a[i+1];
    		}
    		a[n-1]=temp;
 
    		System.out.println("\nNew array after rotating by one postion in the left direction");
    		for(i=0;i<n;i++)
    		{
       	 		System.out.print(a[i]+" ");
    		}
	}	
}

Output

Share Me!