Go Down

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

adamohern

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!

halley

#1
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(); }

adamohern


Oracle

#3
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