Shift elements of an array to Right in Java

In this tutorial, we will learn how we can shift the elements of an array to right using loops in Java.
In this problem, we shift each of the elements of the array to right with the number of shifts specified by the user.

Example 1:
If an array consists of elements arr = {1, 2, 3}, then on shifting these elements towards the right direction by one we would get arr = {3, 1, 2}.

Example 2:
If an array consists of elements arr = {20, 30, 10, 40}, then on shifting these elements towards the right direction by three we would get arr = {30, 10, 40, 20}.

Code to Shift elements of an array to Right in Java

```import java.util.*;
class shift
{
public static void main(String[]mari)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int size = scan.nextInt();
int[]arr = new int[size];

System.out.print("Enter the elements of array: ");
for(int i = 0; i < size; i++)
{
arr[i]=scan.nextInt();
}

System.out.print("Enter number of times to be shifted: ");
int shift = scan.nextInt();
int[] temp = new int[size];
int j = 0;

while(shift >= size)
{
shift = shift - size;
}

for(int i = 0; i < size; i++)
{
if(size - shift + i >= size)
{
temp[i] = arr[j];
j = j + 1;
}

else
{
temp[i] = arr[size - shift + i];
}
}
System.out.print("The shifted array is: ");
for(int i = 0; i < size; i++)
{
System.out.print(temp[i]+" ");
}
System.out.println();
}
}```

Output:

```Enter the size of array: 6
Enter the elements of array: 1 2 3 4 5 6
Enter number of times to be shifted: 5
The shifted array is: 2 3 4 5 6 1```
```Enter the size of array: 4
Enter the elements of array: 1 2 3 4
Enter number of times to be shifted: 4
The shifted array is: 1 2 3 4```
```Enter the size of array: 3
Enter the elements of array: 9 5 1
Enter number of times to be shifted: 1
The shifted array is: 1 9 5

```

Explanation

1. Firstly we declare the size of the array and create an array ” arr ” and store the elements of the array in it.
2. Next scan the shift variable which denotes the number of times the array is supposed to be rotated.
3. Create another array called ” temp ” and check if shift is greater than the size of the array. If so using a while loop decrement the value of shift.
4. Then store the elements of the initial array ” arr ” in the ” temp ” array by using the logic below.
5. In the end, print the elements in the ” temp ” array which contains the shifted elements of the initial array.

Hope you understand the code ðŸ™‚

One response to “Shift elements of an array to Right in Java”

1. Botossi says:

This piece of code:
while(shift >= size)
{
shift = shift – size;
}

can be replaced by :

“int shift = shift % size;”