Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?.

like image 385
Ganesh Thampi Avatar asked Dec 14 '25 01:12

Ganesh Thampi


2 Answers

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
like image 88
John Zwinck Avatar answered Dec 16 '25 19:12

John Zwinck


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
like image 43
Vlad from Moscow Avatar answered Dec 16 '25 19:12

Vlad from Moscow