Shift elements of an array to Left in Java

In this tutorial, we will learn how we can shift the elements of an array to left using loops in Java.
In this problem, we shift each of the elements of the array to left with the number of shifts specified by the user.

Example 1:
If an array consists of elements arr = {1, 2, 3}, then on shifting these elements towards the left direction by one we would get arr = {2, 3, 1}.

Example 2:
If an array consists of elements arr = {20, 30, 10, 40}, then on shifting these elements towards the left direction by three we would get arr = {40, 20, 30, 10}.

 

Code to Shift elements of an array to Left in Java

import java.util.*;
class leftShift
{
  public static void main(String[]args)
  {
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter the size of the array: ");
    int size = scan.nextInt();
    
    int[]arr = new int[size];
    System.out.print("Enter the elements of the array: ");
    for(int i = 0; i < size; i++)
    {
      arr[i] = scan.nextInt();
    }

    int[]temp = new int[ size ];
    System.out.print("Enter the number of times to be shifted: ");
    int shift = scan.nextInt();
    
    while(shift >= size)
    {
      shift = shift - size;
    }

    int j = 0;
    for(int i = 0; i < size; i++)
    {
      if(shift + i >= size)
      {
        temp[i] = arr[j];
        j = j + 1;
      }
      else
      {
        temp[i] = arr[shift + i];
      }
    }
    System.out.print("The shifted array is: ");
    for(int i = 0 ;i < size; i++)
    {
      System.out.print(temp[i] + " ");
    }
  }
}

 




Output:

Enter the size of the array: 6
Enter the elements of the array: 1 5 2 3 4 9
Enter the number of times to be shifted: 3
The shifted array is: 3 4 9 1 5 2
Enter the size of the array: 3
Enter the elements of the array: 9 3 1
Enter the number of times to be shifted: 5
The shifted array is: 1 9 3 

Explanation

  1. Firstly we declare the size of the array and create an array ” arr ” and store the elements of the array in it.
  2. Next scan the shift variable which denotes the number of times the array is supposed to be rotated.
  3. Create another array called ” temp ” and check if shift is greater than the size of the array. If so using a while loop decrement the value of shift.
  4. Then store the elements of the initial array ” arr ” in the ” temp ” array by using the logic below.
  5. In the end, print the elements in the ” temp ” array which contains the shifted elements of the initial array.

 

Hope you understand the code 🙂
Any questions feel free to let us know in the below comment section.

You can also read:


Leave a Reply

Your email address will not be published. Required fields are marked *