Java Program to Left Rotate the Elements of an Array

In the previous article, we have seen Java Program to Find Sum of Two Arrays Elements

In this article we will see how to left rotate all the elements of an array using Java.

Java Program to Left Rotate the Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Approach:

  • Create an array.
  • Display it to the user.
  • Store the first element of the array in a temp variable.
  • Traverse through the array and store each element at its previous index.
  • Set the last index to the value store in our temp variable.
  • Print the array.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        int arr[] = {10,30,50,70,90};
        // Displaying the array
        System.out.print("Array : ");
        printArray(arr);
        // Left rotation
        leftRotation(arr);
        System.out.print("After left rotation, Array : ");
        printArray(arr);

    }

    // Function to print the array
    static void printArray(int arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    // Function to rotate the array
    public static void leftRotation(int arr[])
    {  
        // Holder for first element
        int temp = arr[0];
        // For loop to swap elements
        for (int i=1; i<arr.length; i++)
        {
            arr[i-1]=arr[i];
        }
        // Setting the last element
        arr[arr.length-1]=temp;
    }  
}

Output:

Array : 10 30 50 70 90 
After left rotation, Array : 30 50 70 90 10

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: