Rotate Array by n elements

Description:

Given an array of size n, rotate it by d elements. Input: The first line of the input contains T denoting the number of testcases. First line of test case is the number of elements 'n' and elements 'd' to be rotated. Second line of test case will be the array elements. Output: Rotated array is displayed to the user. Constraints: 1 <=T<= 50 1 <=n<= 100 d<=n 1 <=arr[i]<= 100 Test Case 1 Input (stdin) 5 2 1 2 3 4 5 Expected Output 3 4 5 1 2 Test Case 2 Input (stdin) 10 3 2 4 6 8 10 12 14 16 18 20 Expected Output 8 10 12 14 16 18 20 2 4 6

Program :


import java.io.*;

import java.util.Scanner;

public class TestClass {

void leftRotate(int arr[], int d, int n)

    {

        for (int i = 0; i < d; i++)

            leftRotatebyOne(arr, n);

    }

 

    void leftRotatebyOne(int arr[], int n)

    {

        int i, temp;

        temp = arr[0];

        for (i = 0; i < n - 1; i++)

            arr[i] = arr[i + 1];

        arr[i] = temp;

    }

 

    /* utility function to print an array */

    void printArray(int arr[], int n)

    {

        for (int i = 0; i < n; i++)

            System.out.print(arr[i] + " ");

    }

 

    // Driver program to test above functions

    public static void main(String[] args)

    {

        TestClass rotate = new TestClass();

      Scanner sc=new Scanner(System.in);

        int arr[] =new int[100];

      int n=sc.nextInt();

      int a=sc.nextInt();

      for(int i=0;i<n;i++)

        arr[i]=sc.nextInt();

        rotate.leftRotate(arr, a, n);

        rotate.printArray(arr, n);

    }

}