Go Down

Topic: if a number is even... if it's odd.... (Read 9562 times) previous topic - next topic


Simple question for one of you code gurus out there:

I want an if-then statement that will allow me to test if a given number is even, for example:

Code: [Select]
for (i=0; i<1000; i++)
if (i IS EVEN) { Do something }

Thanks in advance!


Jan 17, 2009, 07:36 pm Last Edit: Jan 17, 2009, 07:37 pm by halley Reason: 1
A number is "even" when you can divide it by two and have zero remainder.

Code: [Select]
if ( (i % 2) == 0) { do_something(); }

A number is "even" if the least significant bit is zero.

Code: [Select]
if ( (i & 0x01) == 0) { do_something(); }



Jan 19, 2009, 04:36 pm Last Edit: Jan 19, 2009, 04:36 pm by Oracle Reason: 1
Also "0" is false, "anything but 0" is true, so:

Code: [Select]
if (i % 2) { // do something odd }

should also work.

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131