Coders Packet

Rotating an array leftward in C++


Rotate an array element towards left side according to the number of shifts given. The array elements shifts towards left side by number of positions given by user.

The code helps us in rotating an array element by the number of shifts, "d" we want it to rotate by.

Firstly, we define a function rotateLeftByOne which rotates the array element by one position. This is done by declaring a temp variable and assigning it the zeroeth position initially i.e arr[0]. Then we run a for loop from i=0 to i=n and inside the for loop we assign the ith array to i+1th array element that is just left to the ith position. This way, the array at ith position is rotated left by one position.

Now after coming out of for loop we assign temp value to arr[i] and process continues for every next array element and this way all the elements shif left by one position.

Now we make function rotateLeft where we rotate array elements by "d" number of shifts as decided by the user. To do this we run a for loop from i-0 to i=d and call rotateLeftByOne function inside it and hence the elements shifts by d number of steps.

Then we print the shifted array by making a function printArray.

In the main function now, simply call the rotateLeft function to do shifting operation and then call print array element to print shifted array.

Download project

Reviews Report

Submitted by SHIVANI KUMARI (shivaniiiii1)

Download packets of source code on Coders Packet