java array traversal in circular manner
int start = ...
for (int i = 0; i < a.length; i++) {
System.out.println(a[(start + i) % a.length]);
}
(If you want to iterate the array backwards from start
, change start + i
to start - i
in the array subscript expression.)
I should note that this is probably not the most efficient way of expressing the loop ... in terms of execution speed. However, the difference is small, and most likely irrelevant.
A more relevant point is whether using %
in this way gives more readable code. I think it does, but maybe that's because I've seen / used this particular idiom before.
How about the following:
int start = // start position, must be in bounds
int i = start;
do {
....
i++;
if(i == a.length) i = 0;
} while(i != start);