# Circular Shifting of Array Contents

Good afternoon,

If someone could help me it would be lovely. I need to make an iterative circular shifting of the contents of an array.

Let’s suppose my array is:

int array = {0, 1, 2, 3, 4, 5}

On the first iteration I want to get
{5, 0, 1, 2, 3, 4 }
on the second
{4, 5, 0, 1, 2, 3 }
on the third
{3, 4, 5, 0, 1, 2 }
and so on…

Thank you in advance,

André

Off-hand I can think of two ways. Either shift the contents (probably wasteful), or use a modulo operator on the array index.

``````const int elements = 6;
int array[] = {0, 1, 2, 3, 4, 5}
int iteration = 1;

void loop() {
item1 = array[ elements - ((0 + iteration) % elements) ];
item2 = array[ elements - ((1 + iteration) % elements) ];
item3 = array[ elements - ((2 + iteration) % elements) ];
etc..

iteration++;
}
``````

(Could use a for-loop for array access ofc).

At least, I think that should work.

Try this (not tested) although there may be other better solutions…

``````int myarray[] = {0, 1, 2, 3, 4, 5};
int number = 0;

void displayArray () {
for (int i = 0; i < number; i++) {
Serial.print(myarray[i]);
Serial.print (" ");
}
Serial.println (" ");
}

void setup() {
Serial.begin(115200);
number = sizeof(myarray) / sizeof(int);
displayArray ();
}

void loop() {
int tempo = myarray[number - 1];
for (int i = number - 1; i > 0; i--) myarray[i] = myarray[i - 1];
myarray[0] = tempo;
displayArray ();
delay(2000);
}
``````

Thank you Raron and Lesept!!

Lesept, your code flows like a charm!!!

Cheers,

André

A more efficient way is to keep track of a start and an end index of your array. For every shift, increase both by 1, roll over if need to, and ... done.