Rotate Array Elements
This program rotates array elements to the left by 2 positions.
Problem Statement
Write a Java program to rotate an integer array to the left by 2 positions.
Source Code
| 1 | public class ArrayRotation { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {1, 2, 3, 4, 5}; |
| 4 | int d = 2; |
| 5 | int[] rotated = new int[arr.length]; |
| 6 | for(int i=0; i<arr.length; i++) { |
| 7 | rotated[i] = arr[(i+d)%arr.length]; |
| 8 | } |
| 9 | System.out.print("Rotated array: "); |
| 10 | for(int num : rotated) System.out.print(num + " "); |
| 11 | } |
| 12 | } |
Program Output
Rotated array: 3 4 5 1 2
Explanation
The variable d stores the rotation distance, and the formula (i+d)%arr.length calculates each new index, so elements are effectively shifted left by 2 positions, demonstrating a rotation operation.