Java program to program to cyclically rotate an array by one

Java 8Object Oriented ProgrammingProgramming

The array is cyclically rotated clockwise by one. This means that each of the array elements are displayed to the right by one and the last element ends up as the first element. An example of this is given as follows.

Original array = 1 2 3 4 5 6 7 8 9 10
Rotated array = 10 1 2 3 4 5 6 7 8 9

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      int n = arr.length;
      int last, i;
      System.out.print("The original array is: ");
      for (i = 0; i < n; ++i)
      System.out.print(arr[i] + " ");
      last = arr[n-1];
      for (i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
      arr[0] = last;
      System.out.print("\nThe rotated Array is: ");
      for (i = 0; i < n; ++i)
      System.out.print(arr[i] + " ");
   }
}

Output

The original array is: 1 2 3 4 5 6 7 8 9 10
The rotated Array is: 10 1 2 3 4 5 6 7 8 9

Now let us understand the above program.

First the original array is displayed. The variable last stores the last element of the array. The code snippet that demonstrates this is given as follows.

System.out.print("The original array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
last = arr[n-1];

Then for loop is used to move all the elements to the right by one position. The 0 index of the array stores the last element. The code snippet that demonstrates this is given as follows.

last = arr[n-1];
for (i = n-1; i > 0; i--)
arr[i] = arr[i-1];
arr[0] = last;

Finally, the rotated array is displayed. The code snippet that demonstrates this is given as follows.

System.out.print("\nThe rotated Array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
raja
Published on 06-Dec-2018 12:17:14
Advertisements