Right Rotate an Array in Java - The Coding Shala
Home >> Java Programs >> Right Rotate an Array
In this post, we will learn how to right rotate the elements of an array using the Java program.
Right Rotate an Array in Java
Write a Java program to Right Rotate the elements of an array by 1 position.
Example:
Input: [1, 2, 3, 4, 5]Output: [5, 1, 2, 3, 4]
Solution 1
We need to rotate the elements to the right by 1 position. We can store the last element in one variable and using for loop will shift all the elements to the right by 1 position.
syntax: arr[i] = arr[i-1]
After shifting all the elements move the last element[stored in variable] to the first index.
Java Program:
/** * https://www.thecodingshala.com/ */ import java.util.*; public class Main { public static int[] rightRotate(int[] arr) { // last element will become first int last = arr[arr.length-1]; for (int i = arr.length-1; i > 0; i--) { // shift the elements to right arr[i] = arr[i-1]; } arr[0] = last; return arr; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("Array before rotation: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println("\nArray after right rotation by 1: "); arr = rightRotate(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Output:
Array before rotation: 1 2 3 4 5 Array after right rotation by 1: 5 1 2 3 4
- Left Rotate an Array in Java
- How to Take 2D Array Input in Java
- Java Program to Print the Sum of all the Elements of the Array
- Java Program to Reverse a String
- Java Program to Reverse an Array
Comments
Post a Comment