calmchess Posted February 11, 2013 Share Posted February 11, 2013 lets say i have a for loop and within that for loop I want 1 action to happen on the odd iterations and a diffrent one to happen on the even iterations. How would I write such a for loop? for(i=0; i<length; i++){ if odd if even } Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 11, 2013 Share Posted February 11, 2013 (edited) Use the modulus operator: Use the modulus operator: for(i=0; i<length; i++) { if(i%2) { //Even code } else { //Odd code } } In case you are not familiar with modulus, it is the mathematical operator to get the remainder of a division. Do, the modulus of 11 divided by 3 would be 2: 11 / 3 = 3 (3 x 3 = 9) with a remainder of 2. So, the modulus of 2 as i increases will alternate between 1 and 0 (no remainder). Since 1 and 0 are interpreted as the logical true/false you can just use the result of the modulus in the if statement rather than if(i%2 == 1) Edited February 11, 2013 by Psycho Quote Link to comment Share on other sites More sharing options...
calmchess Posted February 11, 2013 Author Share Posted February 11, 2013 thank you very much Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.