C / C++ FAQs & Programming Resources - ProkutFAQ : EvenOddWithoutOperators

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links
basbocl

How to find whether given number is even or odd without using any operator?


This can be done by using a bit-field object in structure as below:
#include<stdio.h>
struct myNum
{
    int d:1; /*declare d to have only one bit length */
};

int main()
{
    int val;
    printf("Enter an integer value:\n");
    scanf("%d",&val);

    if(isOdd(val) )
    {
        printf("Given number is an Odd number\n");
    }
    else
    {
        printf("Given number is an Even number\n");
    }
    return 0;
}

int isOdd(int val) /*Returns true if val is odd */
{
    struct myNum n;
    n.d=val;
    return n.d;
}

Explanation:
In the above program, the structure myNum is defined with a bit-field object d with length of 1 bit. When we assign any value to that object, the bits that cannot be accommodated in it are discarded. So, what remains is just least significant bit which can be used to determine whether the number assigned is even or odd.

Example:
If you enter a value 14, then its binary representation would be:
1110
When this value is assigned to the bit-field object d, it discards 111 and only stores the last digit 0.

Similarly if you enter a value 9,
then its binary representation would be:
1001
When this value is assigned to the bit-field object d, it discards 100 and only stores the last digit 1.

This last digit can be used to determine whether its odd or even by using a if condition statement as above.


CategoryPuzzles
 Comments [Hide comments/form]
I got an error here .

scanf("%d",&n.d); but an error occurs that it is illegal to acess the adress of a bit field
-- 220.226.12.217 (2007-07-31 10:42:39)
Well, the '.' also happens to be an operator, so we really can't call this solution to have satisfied the question. :)

Still well done.

Aamrun
-- 121.246.211.45.pune-static.vsnl.net.in (2008-11-28 05:35:18)
Page was generated in 0.0263 seconds