In this tutorial you will learn about the Java Program to right rotate the elements of an array and its application with practical example.
In this tutorial, we will learn to create a Java Program to right rotate the elements of an array using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Rotate an array right means?
Example:
Array=> [1, 2, 3, 4, 5].
Rotate Rights=> [2, 3, 4, 5, 1].
Java Program to right rotate the elements of an array
In this program we will shift right element in an array using for loop. We would first declared and initialized the required variables. Next, we will shift element of an array. Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// java program to swap elements of an array to right import java.util.Arrays; class Main { // Function to right-rotate an array by one position public static void RotateIright(int[] a) { //rotate one position right int last = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) { a[i + 1] = a[i]; } a[0] = last; } // Function to right-rotate an array by `one right` positions public static void rightRotate(int[] a, int rotby) { // base case: invalid input if (rotby < 0 || rotby >= a.length) { return; } for (int i = 0; i < rotby; i++) { RotateIright(a); } } public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5}; int rotby = 1; rightRotate(a, rotby); System.out.println(Arrays.toString(a)); } } |
Output
Right rotated array[]
In the above program, we have first declared and initialized a set variables required in the program.
- a[]= it will hold array values
- rotby= it will hold rotation position.
- i = for iteration
- last = it will hold length of an array[].
After declaring variables we initiate values in an array[]
after that we will call rightRotate(a,rotby) where we pass two arguments one array and another is rotate by value i.e how many time rotate the array to its right.
In an array, if rotby is “1” then, elements of an array moved to its right by one position it mean first element of array take second(2) position, the second element will be moved to the third position and so on. as shown down below->
Array=> [1, 2, 3, 4, 5].
Rotate Rights=> [2, 3, 4, 5, 1].
Finally print right rotated array .