info@meritcampus.com    +91-85006-22255
...
`

Write a program to rotate elements of given array to left by K positions.

Input (int[], int) Output (int[])
{1, 2, 3, 4, 5, 6, 7, 8}, 2 {3, 4, 5, 6, 7, 8, 1, 2}
{1, 2, 3, 4, 5, 6, 7, 8}, 5 {6, 7, 8, 1, 2, 3, 4, 5}
{20, 6, 8, 11, 30}, 3 {11, 30, 20, 6, 8}
{12, 15, 19, 1, 33}, 1 {15, 19, 1, 33, 12}
{5, 6, 7, 8, 9, 10}, -2 {5, 6, 7, 8, 9, 10}
{4, 6, 5, 7, 1}, 11 {6, 5, 7, 1, 4}

``` class RotateArrayElementsLeftByKPositions {     public static void main(String s[])    {        int inputArray[] = {3, 4, 5, 6, 7, 8};        int k = 5;        rotateLeft(inputArray, k);        System.out.println("After rotating array to left by " + k + " postions we get");        for (int element : inputArray)        System.out.print(element + " ");    }     public static void rotateLeft(int inputArray[], int k) { ```
```     } } ```
Topic:

### User comments below.All of them might not be correct.

*if k is negative r array size is 0 than return;
*take an array with the same size
* k%=inputArray.length;(if the given k is moe than size than we can reduce it)
* now start loop from the i=k to till the end array
*take and index variable to store the values into new array
*copy the elements of given array into new array from the position k
* now tak another loop start from the 0 and till the k copy the elements..
* finally copy new array into old array

Posted by Uday Kumar    2015-02-09 06:22:19

here first check k>0 and array size also greater than 0
after if k value is greater than  array size  then divide k with array size and store remainder on in k
k=(k%arraysize)
inputarray[5]={1,2,3,4,5}
k=2
then create a temporary array with size of k temp[2]
and take  values from inputarray[] from first k values and store in temp[] array
next in inputarray store in this
inputarray[o]=inputarray[k]
inputarray[1]=inputarray[k+1] .... upto k value<inputarray size
after completing this
again in inputarray[] remaing cells will fill with temporary array values from temp[] array array
let t=(inputarraysize)-k;
inputarray[t++]=temp[i] (from i=0 to k-1)
here after input array values will be in the order of kth left shifting order
ex:
inputarray[5]={1,2,3,4,5},k=2
1.temp[2]={1,2}
2.inputarray[]={1,2,3,4,5}( kth values store in 0th location k+1 in 1st location soon upto k reaches input size)
then result isinputarray[]={3,4,5,4,5};
3,store temp array values in input array from (inputarray.size-k) to inputarray.size
ex:inputarray[size-k]=temp[i]=> inputarray[3]=temp[0] continue upto i to k-1
result:inputarray[]={3,4,5,1,2};

Posted by Goutham Singarapu    2015-02-09 17:11:18

This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Goutham Singarapu,  for 'Second Correct Comment'. The 'lucky liker' is Maheshwari Natarajan. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-02-10 04:39:32