2
int doEveryTwoTimes= 1;  // Counter to do something every two loops
int doEveryFourTimes= 2; // Counter to do something every four loops 

// add a nested infinite loop to increment counter
while(true){
    if(doEveryTwoTimes%2 == 0){
        // DO STUFF EVERY **TWO** LOOPS
    }

    if(?????){
        // DO STUFF EVERY **FOUR** LOOPS
    }

    doEveryTwoTimes++;
    doEveryFourTimes++;
}

I can add a condition to make things happen every two loops, but how do I create a condition for every fourth loop?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Hooplator15
  • 1,540
  • 7
  • 31
  • 58

1 Answers1

10
if (count % 4 == 0) {
    // Stuff
}

The key being that acting every n loops is accomplished by using mod n == 0, for any n. (Strictly speaking, you can test against any number less than n, but 0 is convenient because it's always less than n, for any natural number n.)

Also, you only need one counter for any number of such actions, since the counter is incremented independently of all of them.

You could even use an unconditional for loop as follows:

for (int count = 0; true; count++) {
    if (count % 2 == 0) {
        // Stuff every other loop
    }
    if (count % 4 == 0) {
        // Stuff every fourth loop
    }
}

It will overflow silently from time to time, but that won't make any real difference to moduli that are powers of 2. But if you want to do something every fifth loop, you'll get weird glitches every time it rolls over. To fix that, find the least common multiple of the various intervals you're using (for all possible intervals up to 12, 27720 is fine) and use that like this:

while (true) {
    for (int count = 0; count < 27720; count++) {
        if (count % 5 == 0) {
            // Stuff every fifth loop
        }
        if (count % 12 == 0) {
            // Stuff every twelfth loop
        }
    }
}

This ensures that all the moduli hit 0 right at the same time, just when you're starting another loop at 0. (The least common multiple gets very large quite quickly with lots and lots of intervals, and you may have to use longs or long longs to store the counter. long long and a maximum of 5342931457063200 should allow you to trigger a different code path for every one of the intervals from 2 to 40 in the same loop. If you need more intervals than that, you'll need to run separate counters.)

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38