#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?.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With