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 Java program for finding the circular rotations of array by k positions 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].
Keypoints:-
In this section we will learn about basic knowledge which we need to know before coding the above Program. So we must have knowledge of what is an array?
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.
Code of Java program for finding the circular rotations of array by k positions
class Main { /*Function to left rotate arr[] of size n by d*/ static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static 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[n - 1] = temp; } /* utility function to print an array */ static 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) { // RotateArray rotate = new RotateArray(); int arr[] = {1, 2, 3, 4, 5}; leftRotate(arr, 2, 5); printArray(arr, 5); } }
Output: 3 4 5 1 2
Login/Signup to comment
import java.util.*;
public class arrrotation{
public static void main(String[] args){
int a[] = new int[6];
Scanner sc = new Scanner(System.in);
System.out.println(“Enter Array element”);
for (int i=0; i<a.length; i++){
a[i] = sc.nextInt();
}
int temp[] = new int[6];
System.out.println("Enter array location");
int d;
d = sc.nextInt();
int k = 0;
for (int i=d; i<temp.length; i++){
temp[k] = a[i];
k++;
}
for (int i=0; i<d; i++){
temp[k] = a[i];
k++;
}
for (int i= 0; i<temp.length; i++){
a[i] = temp[i];
}
for (int i=0; i<temp.length; i++){
System.out.print(a[i] + " ");
}
}
}
class Main {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5 };
int l = arr.length;
int k = 2;
for (int i = 0; i < k; i++) {
int temp = arr[0];
for (int j = 0; j < l – 1; j++) {
arr[j] = arr[j + 1];
}
arr[l – 1] = temp;
}
for (int i = 0; i < l; i++) {
System.out.print(arr[i] + " ");
}
}
}