Ganesh Thampi
Ganesh Thampi

Reputation: 111

Even-odd program using bitwise

#include <stdio.h>

int main()
{
   int n;

   printf("Input an integer\n");
   scanf("%d", &n);

   if (n & 1 == 0)
      printf("even\n");
   else
      printf("odd\n");

   return 0;
}

This program doesn't enter the If loop and always prints 'odd'. I understand that if(False) or if(0) is breaking condition but "n&1==0" is a TRUE condition for even numbers right? or am I missing something here?.

Upvotes: 2

Views: 1204

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

The equality operators == and != have a higher priority than the bitwise AND operator.

So the condition in the if statements is equivalent to the following

if (n & ( 1 == 0 ) )

as 1 is not equal to 0 then the condition can be further rewritten like

if (n & 0)

Thus the substatement of the if statement is never executed because n & 0 always evaluates to false ( 0 ).

To escape the logical mistake you could exchange the if and else statements.

   if (n & 1 )
      printf("odd\n");
   else
      printf("even\n");

Take into account that according to the C Standard the function main without parameters shall be declared like

int main( void )

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    while ( 1 )
    {
        int n;

        printf( "Input an integer (0 - exit): " );

        if ( scanf( "%d", &n ) != 1 || n == 0 ) break;

        printf( "%d is %s\n\n", n, n & 1 ? "odd" : "even" );
    }

    return 0;
}

Its output might look like

Input an integer (0 - exit): 10
10 is even

Input an integer (0 - exit): 9
9 is odd

Input an integer (0 - exit): 8
8 is even

Input an integer (0 - exit): 7
7 is odd

Input an integer (0 - exit): 6
6 is even

Input an integer (0 - exit): 5
5 is odd

Input an integer (0 - exit): 4
4 is even

Input an integer (0 - exit): 3
3 is odd

Input an integer (0 - exit): 2
2 is even

Input an integer (0 - exit): 1
1 is odd

Input an integer (0 - exit): 0

Upvotes: 3

0___________
0___________

Reputation: 67476

you do not have to compare to zero. Any non zero value is the true, zero is false.

So it is enough to:

   if (n & 1 )
      printf("odd\n");
   else
      printf("even\n");

or

printf("%s\n", (n&1) ? "odd" : "even");

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

& has a surprisingly low precedence so you need (n & 1) == 0. Better still, use

if (n & 1)
      printf("odd\n");
else
      printf("even\n");

Note that this is implementation defined for negative int values due to differing complementing schemes, so you may well not get a correct answer for a negative n. Perhaps use unsigned?

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249143

Enable all warnings in your compiler. Mine says:

warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
note: place parentheses around the & expression to evaluate it first

Upvotes: 4

Related Questions