Circular for a cycle in C

I am interested in iterating the list in such a way that I can start at any position and iterate over the entire list, going up to the end, and then returning to the beginning and iterating to the starting position.

Let's say I want to do this for an array that is guaranteed 4 elements: char array [4] = {'a', 'b', 'c', 'd'}

I find it difficult to create a for loop so that I can start with 'a', and the abcd cycle either start with 'b', and the bcda cycle, or start with d, and the dabc cycle, etc.

I think the start of the for loop will look like i = startPosition.

I think that the incremental part of the for loop will look like i = (i + 1)% 4. So, starting from index 2, for example, to 3, then 0, then 1, etc.

What should be the termination condition, "completion"?

for(i = startingPosition; ???; i = (i+1)%4) 

Thanks!

+7
c for-loop circular-list
source share
2 answers

Use normal iteration to control the path, then adjust the index modulo size:

 for (i = 0; i < size; i++) { int index = (i + startingPosition) % size; // Do stuff with array[index] } 
+15
source share
 i = startingPosition; do { // use 'i' here i = (i + 1) % size; } while (i != startingPosition); 
+4
source share

All Articles