Java Program to right rotate the elements of an array

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?

Array is said to be right rotated if elements in an array are moved to its right >> by one(1) position.

 

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.

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 .

In this tutorial we have learn about the Java Program to right rotate the elements of an array and its application with practical example. I hope you will like this tutorial.