how-to

Math

How to use modulo operator - is a number even or odd ?

Modulo operator finds the remainder of division of one number by another. This technique is very useful in many occations - here is shown code how to check if a number value is even or odd:

int iValue = 35;

/* -- check if the value is even */

boolean isEven = ( ( iValue % 2 ) == 0 );

if ( isEven )
  System.out.print( "Value is even." );
else
  System.out.print( "Value is odd." );

The output will be:

Value is odd.
NOTE: Other variant for checking even/odd is by bitwise operation (checking if is/isn`t set lowest bit):
isEven = ( ( iValue & 1 ) == 0 );