In this tutorial, we will write a **java program to right rotate the elements of an array by a specified number**. For example, if we are right rotate an array` {10, 20, 30, 40 ,50}`

by `n =1`

then the output array would look like this: `{50, 10, 20, 30, 40}`

.

The concept is similar to the left rotation, except that the elements are shifted to right in right rotation. All the elements are **shifted to the right by the specified number** `n`

, in the above example all elements are shifted to the right by 1 position. If **n = 2**, then the elements shift to right by **two positions **and last two elements would be shifted to the beginning of the array.

Let’s take few example to understand the concept and then we will write a program to implement this:

Let's say an Array is {11, 22, 33, 44, 55, 66} Right rotate by 2 After first rotation: {66, 11, 22, 33, 44, 55} After second rotation: {55, 66, 11, 22, 33, 44} Output array would be {55, 66, 11, 22, 33, 44} Note that the last elements are shifted to the start of the array. Let's Right rotate the same array by 3 Array is {11, 22, 33, 44, 55, 66} After first rotation: {66, 11, 22, 33, 44, 55} After second rotation: {55, 66, 11, 22, 33, 44} After third rotation: {44, 55, 66, 11, 22, 33} Output array would be {44, 55, 66, 11, 22, 33}

## Program to Right rotate the elements of a given array

In the following example, we have initialized an array and we have a **number n that represents the number of times the array should be right rotated**.

We run a loop from 0 till the number n (specifies the right rotation count) and at each iteration of this loop, we shift the element to the right by one position.

Which means, the first element would move to 2nd position, second element would move to 3rd position and so on. Before shifting any element, **we store the last element in a different variable lastElement which we add at the beginning of the array**.

class JavaExample { public static void main(String[] args) { //Initializing the array numbers int [] numbers = new int [] {11, 22, 33, 44, 55, 66}; /* This number specifies how many times the array needs * to be right rotated. */ int n = 2; System.out.println("Given array is: "); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } //Right rotate the array by n times for(int i = 0; i < n; i++){ int j, lastElement; //Storing the last element of the array to move to start lastElement = numbers[numbers.length-1]; for(j = numbers.length-1; j > 0; j--){ //Shifting the element to right by 1 on each iteration of loop numbers[j] = numbers[j-1]; } //Adding the last element at the beginning of the array numbers[0] = lastElement; } System.out.println(); //Printing output array System.out.println("Array after "+n+" right rotations: "); for(int i = 0; i< numbers.length; i++){ System.out.print(numbers[i] + " "); } } }

**Output:**

Given array is: 11 22 33 44 55 66 Array after 2 right rotations: 55 66 11 22 33 44

## Leave a Reply