- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to program to cyclically rotate an array by one
The array is cyclically rotated clockwise by one. This means that each of the array elements are displayed to the right by one and the last element ends up as the first element. An example of this is given as follows.
Original array = 1 2 3 4 5 6 7 8 9 10 Rotated array = 10 1 2 3 4 5 6 7 8 9
A program that demonstrates this is given as follows.
Example
public class Example { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = arr.length; int last, i; System.out.print("The original array is: "); for (i = 0; i < n; ++i) System.out.print(arr[i] + " "); last = arr[n-1]; for (i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = last; System.out.print("
The rotated Array is: "); for (i = 0; i < n; ++i) System.out.print(arr[i] + " "); } }
Output
The original array is: 1 2 3 4 5 6 7 8 9 10 The rotated Array is: 10 1 2 3 4 5 6 7 8 9
Now let us understand the above program.
First the original array is displayed. The variable last stores the last element of the array. The code snippet that demonstrates this is given as follows.
System.out.print("The original array is: "); for (i = 0; i < n; ++i) System.out.print(arr[i] + " "); last = arr[n-1];
Then for loop is used to move all the elements to the right by one position. The 0 index of the array stores the last element. The code snippet that demonstrates this is given as follows.
last = arr[n-1]; for (i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = last;
Finally, the rotated array is displayed. The code snippet that demonstrates this is given as follows.
System.out.print("
The rotated Array is: "); for (i = 0; i < n; ++i) System.out.print(arr[i] + " ");
- Related Articles
- Java program to cyclically rotate an array by one.
- Python program to cyclically rotate an array by one
- JavaScript Program for Program to cyclically rotate an array by one
- Java Program to Rotate an Image
- Golang Program to Rotate Elements of an Array
- Swift Program to Rotate Elements of an Array
- Golang Program to cyclically permutes the elements of the array
- Python program to left rotate the elements of an array
- Python program to right rotate the elements of an array
- Java Program to Rotate Matrix Elements
- Java program to reverse an array
- Java Program to Rotate Elements of a List
- Java program to convert an Array to Set
- Python program to right rotate a list by n
- Java program to convert a list to an array
