Google News
logo
Java Program to Right Rotate the Elements of an Array
In the following example of Java program to right rotate the elements of an array :
Program :
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));
    }
}
Output :
Original Array: [1, 2, 3, 4, 5]
Array after right rotation: [4, 5, 1, 2, 3]
In this program, we have an integer array 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.

Then, we have a loop that runs 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.

In each iteration of the inner loop, we shift the elements of the array one position to the right. Finally, we assign the last element of the array to the first position to complete the rotation.