Test an int to determine if it is even or odd


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 1) > Test an int to determine if it is even or odd

This item was added on: 2003/01/28

This can be done in various ways. Here are a couple:

Division by 2

A number is even if it can be evenly divided by two. So if after division by 2 the remainder is 0, the number is even. One can find the remainder of integer division in C or C++ with the remainder operator (%):

#include <stdio.h> 

int is_even ( int i )
{
  return i % 2 == 0;
}

int main ( void )
{
  int i;

  for ( i = 0; i < 10; i++ ) {
    printf ( "Testing %d...", i );

    if ( is_even ( i ) )
      printf ( "Yep, it's even\n" );
    else
      printf ( "Nope, it's odd\n" );
  }

  return 0;
}

Bitwise AND

For those familiar with binary numbers, the least significant bit always alternates between 0 and 1. Every other number has the same bit setting. Try it and see, I'll wait... Of better yet, here's a program that will show you:

#include <bitset>
#include <climits>
#include <iostream>

int main()
{
  for ( int i = 0; i <= UCHAR_MAX; i++ )
    std::cout<< i <<": "<< std::bitset<8> ( i ) <<'\n';
}

Notice how all the least significant bit in all of the even numbers is 0? That's the revelation required to figure out this little trick for finding an even number:
#include <stdio.h>

int is_even ( int i )
{
  return ( i & 1 ) == 0;
}

int main ( void )
{
  int i;

  for ( i = 0; i < 10; i++ ) {
    printf ( "Testing %d...", i );

    if ( is_even ( i ) )
      printf ( "Yep, it's even\n" );
    else
      printf ( "Nope, it's odd\n" );
  }

  return 0;
}

For more on bitwise operators, check out bitwise operators in C++ or bit manipulation in C++.

Restrictions

Of course, both of these tricks fail to work on floating-point values. The first fails because the remainder operator is not defined for floating-point; you have to use the fmod function instead to take the remainder of floating-point division. The second also fails because bitwise operations are not defined for floating-point. Why you would want to do this on a floating-point value is another question entirely.


Credit: Prelude

Script provided by SmartCGIs