It's probably clearest just to use a break
, then you don't have to worry about all the different cases:
for (int day = startDay; ; day = (day - 1) % 7 + 1) {
// ... do your stuff
if (day == endDay) {
break;
}
}
or, some might prefer this:
int day = startDay;
while (true) {
// ... do something
if (day == endDay) {
break;
}
day = (day - 1) % 7 + 1;
}
or:
int day = startDay;
while (true) {
// ... do something
if (day == endDay) {
break;
}
if (++day > 7) {
day = 1;
}
}
Trying to get all the different cases right with a for
loop can be a headache. You have to make sure these are handled:
startDay == 1, endDay == 7
endDay == startDay
endDay == startDay - 1 (which should go through every day of the week in some order)
endDay > startDay
endDay < startDay