13.Program to right rotate the elements of an array
💡Code:
public class RightRotateArray7078 {
public static void main(String[] args) {
// Example array
int[] array = {1, 2, 3, 4, 5};
// Display the original array
System.out.println("Original Array:");
displayArray(array);
// Right rotate the array by 2 positions
int rotations = 2;
rightRotateArray(array, rotations);
// Display the rotated array
System.out.println("\nArray after Right Rotation:");
displayArray(array);
}
// Method to right rotate the elements of an array
private static void rightRotateArray(int[] arr, int positions) {
int length = arr.length;
int[] temp = new int[length];
// Copy the elements to a temporary array
System.arraycopy(arr, 0, temp, 0, length);
// Right rotate the elements
for (int i = 0; i < length; i++) {
arr[(i + positions) % length] = temp[i];
}
}
// Method to display the elements of an array
private static void displayArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
}
📸Output :