c - How to go about doing something every fourth loop as well as every other loop? -


int doeverytwotimes= 1;  // counter every 2 loops int doeveryfourtimes= 2; // counter every 4 loops   // add nested infinite loop increment counter while(true){     if(doeverytwotimes%2 == 0){         // stuff every **two** loops     }      if(?????){         // stuff every **four** loops     }      doeverytwotimes++;     doeveryfourtimes++; } 

i can add condition make things happen every 2 loops, how create condition every fourth loop?

if (count % 4 == 0) {     // stuff } 

the key being acting every n loops accomplished using mod n == 0, n.

also, need 1 counter number of such actions, since counter incremented independently of of them.

you use unconditional loop follows:

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

it overflow silently time time, won't make real difference moduli powers of 2. if want every fifth loop, you'll weird glitches every time rolls over. fix that, find least common multiple of various intervals you're using (for possible intervals 12, 27720 fine) , use this:

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

this ensures all moduli hit 0 right @ same time, when you're starting loop @ 0. (the least common multiple gets large quite lots , lots of intervals, , may have use longs or long longs store counter. long long should way every last interval 2 40.)


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -