Java Program to Left Rotate an Array

In this tutorial, we will learn how to left rotate a given array in java programming language. So let’s start learning, left rotation of an array in Java.

We need to rotate the elements of an array to the left by a specified number of rotations. For left rotation, we have to shift each element to its left by one position and the first element of the array will be shifted to the end of the array. These steps will be iterative on the array for given number of times.

For example, if n is 1 then all elements of the array will be moved to their left by one position such that second element of the array will be moved to the first position, the third element will be moved to the second position and so on. The first element of the array will be shifted to the last of the array.

Java Code of Left Rotation of an Array

import java.io.*;
import java.util.*;
public class Main {  
    public static void main(String[] args)throws IOException{
        BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
        int [] ar = {6,7,8,9,10};  
        System.out.print("Enter number of rotations: ");
        int n = Integer.parseInt(ob.readLine());
        System.out.println("Original array: ");  
        System.out.print(Arrays.toString(ar));  
            
        for(int i = 0; i < n; i++){  
            int j, first_element;  
            first_element = ar[0];  
            for(j = 0; j < ar.length-1; j++){ 
                ar[j] = ar[j+1];  
            }  
            ar[j] = first_element;  
        }  
        System.out.println();  
        System.out.println("Rotated Array: ");  
        System.out.print(Arrays.toString(ar)); 

    }  
}

 

Output:

Enter number of rotations: 4

Original array: 
[6, 7, 8, 9, 10]
Rotated Array: 
[10, 6, 7, 8, 9]

You might be also interested in:

Adding hours to the current time in Java

Remove all Numbers from a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *