Java Program to perform two left rotations on the array

Java Program to perform two left rotations on the array

In this tutorial we have explained how to write java program to perform left rotation on array element by two position. Here left rotation by two means shifting the array element left side two times.

For Example:

Suppose we have an given array arr = [2, 3, 4, 2, 8]

So output after two times left rotation should be [4, 2, 8, 2, 3]

Java program to perform two times left rotation 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 2
        for(int i=0; i<2; 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 two times 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 : 4
Please give value for index 1 : 1
Please give value for index 2 : 5
Please give value for index 3 : 3
Please give value for index 4 : 2
Array after two times Left rotation
5       3       2       4       1