Clever ways to avoid using if statements

This tip submitted by A. Karthick Pandia Samy on 2005-03-31 01:41:58. It has been viewed 42479 times.
Rating of 6.5 with 206 votes



How could you determine if a number is odd or even without using an if statement or even relational operators like greater than?

There are actually several ways:

Method 1:
=========
int main()
{
   char *result[2] = { \"Even\", \"Odd\" };
   int no;
   scanf( \"%d\", &no );

   printf( result[no%2] );
   return 0;
}


Method 2:
=========

int main()
{
  int no;
  scanf( \"%d\", &no );
  no&1 ? printf(\"odd\"):printf(\"Even\");
}




More tips

Help your fellow programmers! Add a tip!