Java Program to perform one left rotation on array

Java Program to perform one left rotation on array

In this tutorial you will be learning writing java program to perform left rotation on the array element by one place.

For example:

Suppose we have an array arr = [ 2, 4, 1, 5, 3]

So output will be [4, 1, 5, 3, 2]

Java Program to perform left rotation by one on array element

import java.util.*;
public class Main{
    public static void main (String[]args){
        Scanner sc = new Scanner (System.in);
        //Taking array size and array element as input
        System.out.println ("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        for ( int i = 0; i < size; i++){
	        System.out.print("Please give value for index " + i + " : ");
	        arr[i] = sc.nextInt();
        }
        //here our logic to perform left rotation by 1
        for(int i=0; i<1; i++)
        {
            int temp=arr[0];
            for(int j=0; j<size-1; j++)
            {
                arr[j]=arr[j+1];
            }
            arr[size-1]=temp;
        }
        System.out.println("Array after one time Left rotation");
        for(int i=0; i<size; i++)
        {
            System.out.print(arr[i]+"\t");
        }
    }
}

Output

Enter the size of array: 
5
Please give value for index 0 : 2
Please give value for index 1 : 3
Please give value for index 2 : 1
Please give value for index 3 : 4
Please give value for index 4 : 3
Array after one time Left rotation
3       1       4       3       2