Home >>Java Programs >Java Program to left rotate the elements of an array
In this program, we will create a Java program to rotate the elements of an array towards the left by the specified number of times.
In the left rotation, each element of the given array will be shifted to its left by one position and the first element of the array will be added to the end of the list. This process will be followed for a specified number of times.
Program:
class Main {
public static void main(String[] args) {
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int n = 5;
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for(int i = 0; i < n; i++){
int j, first;
first = arr[0];
for(j = 0; j < arr.length-1; j++){
arr[j] = arr[j+1];
}
arr[j] = first;
}
System.out.println();
System.out.println("Array after left rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}