Java program for finding the circular rotations of array by k positions

Circular rotation of an array by K position

Here in this program we’ll be learning about Circular array rotation which means rotating the elements in the array where one rotation operation moves the last element of the array to the first position and shifts all remaining elements to the right. Consider the following indexes to be checked [0,1,2].

Example:

Initial array   [1, 2, 3]

After one rotation   [3, 1, 2]

After two rotations   [2, 3, 1]

Java program for finding circular rotation of an array by k position

Algorithm

Step 1- Initialize a class

Step 2- Enter number of elements of array

Step 3- Enter number of rotations of array.

Step 4- Enter number of indexes to be displayed.

Step 5- Input array elements

Step 6- run a for loop, i=0; i< elements; , i++.

step 7- then module your rotations with elements

Step 8- Enter the index of array to be displayed

step 9- print number of indexes and rotations.

 

Java Program

import java.util.*;
public class PrepInsta
{
    public static void main(String[] args) 
    {
        int elements,rotations, display;
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of elements of the array : ");
        no_of_elements = sc.nextInt();

        System.out.println("Enter the number of rotations of the array : ");
        no_of_rotations = sc.nextInt();

        System.out.println("Enter the number of indexes to be displayed : ");
        no_to_display = sc.nextInt();

        int arr[] = new int[no_of_elements];
        System.out.println(" Input the array elements");
        for(int i = 0; i <elements; i++)
        {
            arr[i] = sc.nextInt();
        }

        System.out.println("The Array Elements are");
        for(int i = 0; i <elements; i++)
        {
            System.out.print(arr[i]);
            System.out.print("\d");
        }

        rotations %= elements; // Remove the number of full array rotations from k

        for(int i = 0; i <display; i++)
        {
            int index;
            System.out.println("Enter the index of the array to be displayed : ");
            index = sc.nextInt();

            System.out.println("The element in the array is ");
            System.out.println(arr[(elements + index - rotations) % no of elements]); // Calculate the new index 
        }}}
Output
Enter number of elements of array
5
Enter the number rotations in array
3
Enter the indexes to be displayed
3
Input the elements of array
1  2  3  4  5
The Array Elements are
1 2 3 4 5
Enter the index of the array to be displayed :
2

The element in the array is
5

Enter the index of the array to be displayed :
3

The element in the array is
1

Enter the index of the array to be displayed :
2 3 4

The element in the array is
5