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

Original array arr initialized. - Variable d stores rotation distance. - Formula (i+d)%arr.length calculates new index. - Elements shifted left by 2 positions. - Together demonstrates rotation operation. Conclusion: Shows how arrays can be rotated to manipulate order.

Quick Links to Explore