Pages: [1]   Go Down
Author Topic: if a number is even... if it's odd....  (Read 4764 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 24
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
for (i=0; i<1000; i++)
{
if (i IS EVEN) { Do something }
}

Thanks in advance!
Logged

Connecticut, US
Offline Offline
Edison Member
*
Karma: 2
Posts: 1036
Whatduino
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

A number is "even" when you can divide it by two and have zero remainder.

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

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

Code:
if ( (i & 0x01) == 0) { do_something(); }
« Last Edit: January 17, 2009, 01:37:01 pm by halley » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 24
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Perfect! Thanks!
Logged

0
Offline Offline
God Member
*****
Karma: 2
Posts: 854
Arduino rocks!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Also "0" is false, "anything but 0" is true, so:

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

should also work.
« Last Edit: January 19, 2009, 10:36:57 am by Oracle » Logged

Pages: [1]   Go Up
Jump to: