Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Circular" for loop in C

I'm interested in iterating in a list in such a way that I can start at any position and iterate through the whole list by going up to the end, and then looping back to the beginning and iterating up to the starting position.

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

I'm having difficulty constructing a for loop such that I can start at 'a', and loop abcd, or start at 'b', and loop bcda, or start at d, and loop dabc, etc.

I think the initial part of the for loop would be something like i = startingPosition.

I think the increment part of the for loop would be something like i = (i+1) % 4. That way, starting at index 2, for example, will go up to 3, then 0, then 1, etc.

What should the middle, "terminating" condition be?

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

Thanks!

like image 821
user2823499 Avatar asked Oct 25 '13 23:10

user2823499


2 Answers

Use normal iteration for the loop control, then adjust the index modulo the size:

for (i = 0; i < size; i++) {
    int index = (i + startingPosition) % size;
    // Do stuff with array[index]
}
like image 58
Barmar Avatar answered Nov 04 '22 06:11

Barmar


i = startingPosition;
do
{
    // use 'i' here
    i = (i + 1) % size;
} while (i != startingPosition);
like image 44
David Schwartz Avatar answered Nov 04 '22 08:11

David Schwartz