Hi venkatarao,
A few comments inline, some of which are related to your problem and
others not.
This should read
#include said:
This should read
int main(void)
since we are not in the year 1985.
{
unsigned short value;
scanf("%d",&value);
The "%d" specifier expects to store an `int', but you have passed the
address of an `unsigned short'. The specifier to read an unsigned short
in decimal is "%hu". Also, it would be wise to check the return value
from scanf to make sure that it successfully read a number before
continuing and using that number.
if(value<<15) // for even or odd value every
time its taking +ve value only
This is the key to the problem.
The operands of << are promoted to `int' (or perhaps `unsigned int' or a
larger type) before shifting, and the result is of the same type. This
is most likely larger than 16 bits on your system, so shifting by 15
bits will not get rid of all the higher bits.
As someone else posted, you could do
if ((unsigned short)(value << 15))
If `unsigned short' is indeed 16 bits on your system, this will discard
all but the lowest 16, which should give you an expression which is 0 if
`value' was even, and 32768 if `value' is odd. However, `unsigned
short' is allowed to be larger than 16 bits (though not smaller), so
this won't work either on a system where that is the case.
A much better way to test whether a number is even or odd is to do
if (value % 2 == 0) /* even */; else /* odd */;
or alternatively
if (value & 1 == 0) /* even */; else /* odd */;
These will work no matter what integer type you use for `value'. They
might also be faster; on some systems, shifts are substantially slower
than the logical AND which these two examples will probably use.
printf("given odd value");
else
printf("given even value");
You should include a newline '\n' at the end of your output, otherwise
it will look funny on some systems and cause more severe problems on
others.
After changing the definition of `main' to `int main(void)', you will
need to return a value from the function. `return 0;' or else
output:
for given even or odd value its giving "given odd value" every time
why logical operator not working in if condition.
file.c
#include"stdio.h"
main()
{
unsigned short value,a;
scanf("%d",&value);
a = value<<15;
if( a ) // In this condition working fine
printf("given odd value");
else
printf("given even value");
}
Assigning `value << 15' to a variable of type `unsigned short' also has
the effect of truncating the high bits. But this also will not work if
`unsigned short' is more than 16 bits.