In this program, the goal is to rotate the elements of an array towards the left by a specified number of times. Left rotation involves shifting each element in the array to its left by one position, with the first element being moved to the end of the array. This process is repeated for a specified number of rotations.
If the value of n is 1, the array elements will be shifted towards the left by one position. This means that the second element of the array will take the first position, the third element will be moved to the second position, and so on. The first element of the array will be added to the last position.
Algorithm of a Java Program to rotate the elements of an array to the left
STEP 1: Start
STEP 2: Initialize the array arr[] with values {1, 2, 3, 4, 5}.
STEP 3: Set the value of n to 3.
STEP 4: Print “Original Array”.
STEP 5: Repeat STEP 6 for each index i from 0 to the length of arr[].
STEP 6: Print the value at arr[i].
STEP 7: Repeat STEP 8 to STEP 12 for each rotation (i.e., i from 0 to n).
STEP 8: Define the variables j and first.
STEP 9: Set the value of the first as arr[0].
STEP 10: Repeat STEP 11 for each index j from 0 to the length of arr[] – 1.
STEP 11: Set the value at arr[j] to the value at arr[j+1].
STEP 12: Set the value at arr[j] as first.
STEP 13: Print “Array after left rotation”.
STEP 14: Repeat STEP 15 for each index i from 0 to the length of arr[].
STEP 15: Print the value at arr[i].
STEP 16: End.
Java Program to rotate the elements of an array to the left
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:
Original Array: 1 2 3 4 5 Array after left rotation: 4 5 1 2 3
n conclusion, the Java program provided aims to rotate the elements of an array towards the left a specified number of times. The program follows a step-by-step approach to achieving this task. It initializes an array with given values, specifies the number of rotations, and utilizes a loop to shift the elements toward the left. Each rotation involves storing the first element in a temporary variable, shifting all other elements to the left, and assigning the temporary variable value to the last position in the array.
Follow tutorials.freshersnow.com to learn more.