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!
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]
}
i = startingPosition;
do
{
// use 'i' here
i = (i + 1) % size;
} while (i != startingPosition);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With