JAVA SP T


Lets dive into snapshot of my programs!💻

3.Program to left rotate the elements of an array

💡Code:

  

                public class LeftRotateArray7078 {
                    public static void main(String[] args) {
                        // Example array
                        int[] array = {1, 2, 3, 4, 5};
                
                        // Number of positions to rotate
                        int positionsToRotate = 2;
                
                        // Display the original array
                        System.out.println("Original Array:");
                        displayArray(array);
                
                        // Left rotate the array
                        leftRotateArray(array, positionsToRotate);
                
                        // Display the rotated array
                        System.out.println("\nArray after left rotation:");
                        displayArray(array);
                    }
                
                    // Method to left rotate the array
                    private static void leftRotateArray(int[] arr, int positions) {
                        int length = arr.length;
                        positions = positions % length; // Ensure positions is within array length
                
                        for (int i = 0; i < positions; i++) {
                            int temp = arr[0];
                            for (int j = 0; j < length - 1; j++) {
                                arr[j] = arr[j + 1];
                            }
                            arr[length - 1] = temp;
                        }
                    }
                
                    // Method to display the elements of an array
                    private static void displayArray(int[] arr) {
                        for (int value : arr) {
                            System.out.print(value + " ");
                        }
                        System.out.println();
                    }
                }
                
               

📸Output :

output