import java.util.Arrays;
public class RightRotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = 2;
System.out.println("Original Array: " + Arrays.toString(arr));
for(int i=0; i<n; i++){
int j, last;
last = arr[arr.length-1];
for(j=arr.length-1; j>0; j--){
arr[j] = arr[j-1];
}
arr[0] = last;
}
System.out.println("Array after right rotation: " + Arrays.toString(arr));
}
}
Original Array: [1, 2, 3, 4, 5]
Array after right rotation: [4, 5, 1, 2, 3]
arr
and we want to rotate it to the right by n
positions. Here, we have taken n=2
. We first print the original array using Arrays.toString()
method. n
times to perform the rotation. Inside the loop, we have two nested loops. The outer loop is used to perform the rotation n
times, while the inner loop is used to perform the actual rotation.