Java Program to perform one right rotation on an array

Java Program to perform one right rotation on an array

In this tutorial you will be learning java program to perform right rotation on array element by one.

For example:

Suppose we have given an array arr = [2, 3, 1, 5, 9]

so output should be [9, 2, 3, 1, 5]

Here we have performed right rotation by one position.

Java Program to perform right rotation on array element by 1 position

import java.util.*;
public class Main{
    public static void main (String[]args){
        Scanner sc = new Scanner (System.in);
        //Taking array size and array element as input
        System.out.println ("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        for ( int i = 0; i < size; i++){
	        System.out.print("Please give value for index " + i + " : ");
	        arr[i] = sc.nextInt();
        }
        //here our logic to perform Right rotation by 1
        for(int i=0; i<1; i++)
        {
            int temp=arr[size-1];
            for(int j=size-1; j>0; j--)
            {
                arr[j]=arr[j-1];
		    }
            arr[0]=temp;
        }
        System.out.println("Array after one time Right rotation");
        for(int i=0; i<size; i++)
        {
            System.out.print(arr[i]+"\t");
        }
    }
}

Output

Enter the size of array: 
5
Please give value for index 0 : 3
Please give value for index 1 : 1
Please give value for index 2 : 2
Please give value for index 3 : 3
Please give value for index 4 : 4
Array after one time Left rotation
4       3       1       2       3