In this tutorial you will learn about the Java Program to left rotate the elements of an array and its application with practical example.
In this tutorial, we will learn to create a Java Program to left rotate the elements of an array using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Rotate an array left, means?
Example:
Array⇾ [1, 2, 3, 4, 5].
Rotate left ⇾ [5,1,2,3,4].
Java Program to left rotate the elements of an array
In this program, we will shift the left element in an array using for loop. We would first declare and initialized the required variables. Next, we will shift elements of an array. Let’s have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class RotateLeft { public static void main(String[] args) { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; //n determine the number of times an array should be rotated int n = 3; //Displays original array System.out.println("Original array: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } //Rotate the given array by n times toward left for(int i = 0; i < n; i++){ int j, first; //Stores the first element of the array first = arr[0]; for(j = 0; j < arr.length-1; j++){ //Shift element of array by one arr[j] = arr[j+1]; } //First element of array will be added to the end arr[j] = first; } System.out.println(); //Displays resulting array after rotation System.out.println("Array after left rotation: "); for(int i = 0; i< arr.length; i++){ System.out.print(arr[i] + " "); } } } |
Output
Left rotated array[]
In the above program, we have first declared and initialized a set of variables required in the program.
- arr[]= it will hold array values
- first = it will hold rotation position.
- i = for iteration of the program.
- n = it will hold the integer value for left side.
After declaring variables we initiate values in an array[]
After that, we will call left Rotate(n , first ) where we pass two arguments one array and another is rotated by value i.e. how many times rotate the array to its Left.
In an array, if Lotby is “1” then, elements of an array are moved to its Left by one position it means the first element of the array takes the second(2) position, the second element will be moved to the third position, and so on. As shown down below⇾
Array⇾ [1, 2, 3, 4, 5].
Rotate Left ⇾ [4, 5, 1, 2, 3].
Finally, print the Left rotated array.