|
This is a really simple one, but when I spoke to a developer recently he had completely overlooked the simplest way to discover if an integer is odd or even, and was performing quite a convoluted formula to get the answer.
He had completely overlooked using the built in modulus operator (%) to find the result. This provides the remainder after division, so for an even number after dividing by 2 the remainder will be 0, otherwise it will be 1.
The simplest way to do this is
int myvar;
if(myVar % 2==0) { // its even } else { // its odd }
|
24 November 2009 IB
C#
|
Back To List
Did this article answer your question |
 |
Yes |
 |
No |
|
Other items of interest in our knowledgebase
|