Jump to content

for loop question


calmchess

Recommended Posts

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 by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.