rotate left array java code example

Example 1: array rotation program in java

//Rotating array left 
//d = number of rotations
static void rotLeft(int[] a, int d)
{
    //using secondary array of  same size 
	int [] n = new int[a.length];
    //saving element into array n[] according to newlocation of rotations(d)
	for(int i = 0; i < a.length; i++)
	{
		int newlocation = (i+(a.length - d))% a.length;
		n[newlocation] = a[i];
	}
	//printing new rotated array
	for(int i = 0; i < a.length; i++)
	{
		System.out.print(n[i]+ " ");
	}
}

Example 2: java code to right rotate an array

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) 
	{
	    Scanner sc=new Scanner(System.in);
		// your code goes here
		int arr[]= new int[10];
		arr[0]=5;
		arr[1]=34;
		arr[2]=23;
		arr[3]=6;
		arr[4]=84;
		for(int i=0;i<arr.length;i++)
		{
		    System.out.print(arr[i]+" ");
		    
		}
		System.out.println("");
		for(int i=5;i>=2;i--)
		{
		    arr[i+1]=arr[i];
		}
		arr[2]=15;
		for(int i=0;i<arr.length;i++)
		{
		    System.out.print(arr[i]+" ");
		   
		}
	}
}