Google News
logo
Java Program to Left Rotate the Elements of an Array
In the following example of Java program to left rotate the elements of an array :
Program :
import java.util.Arrays;

public class LeftRotateArray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int n = arr.length;
        int d = 2;
        System.out.println("Original array: " + Arrays.toString(arr));
        
        // left rotate array by d positions
        for (int i = 0; i < d; i++) {
            int temp = arr[0];
            for (int j = 1; j < n; j++) {
                arr[j - 1] = arr[j];
            }
            arr[n - 1] = temp;
        }
        
        System.out.println("Array after left rotation: " + Arrays.toString(arr));
    }
}
Output :
Original array: [1, 2, 3, 4, 5]
Array after left rotation: [3, 4, 5, 1, 2]
In this program, we first declare an integer array arr and initialize it with the values {1, 2, 3, 4, 5}. We get the length of the array n and declare an integer variable d to specify the number of positions to rotate the array.

We use a nested for loop to left rotate the array by d positions. In the outer loop, we repeat the left rotation process d times. In the inner loop, we shift each element of the array one position to the left, except for the first element, which we store in a temporary variable temp. After the inner loop completes, we assign the value of temp to the last element of the array.

Finally, we print the original array and the array after left rotation to the console using System.out.println() and Arrays.toString().