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

HomePage Recent Changes Recently Commented Login/Register

Revision [763]

Most recent edit made on 2008-11-28 05:58:45 by SharathAV

Additions:

return n.d;


Deletions:

if(n.d)
return 1;
return 0;
}




Revision [762]

Edited on 2008-11-28 05:56:43 by SharathAV

Additions:

int d:1; /*declare d to have only one bit length */
int val;
scanf("%d",&val);
if(isOdd(val) )
int isOdd(int val) /*Returns true if val is odd */
n.d=val;
return 1;
return 0;
}


Deletions:

int d:1;
scanf("%d",&n.d);




Revision [593]

Edited on 2007-11-12 02:46:11 by CatroUtrou (unregistered user)

Additions:
basbocl




Revision [372]

The oldest known version of this page was edited on 2007-06-05 14:16:32 by SharathAV

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;
};

int main()
{
    struct myNum n;
    printf("Enter an integer value:\n");
    scanf("%d",&n.d);
    if(n.d)
    {
        printf("Given number is an Odd number\n");
    }
    else
    {
        printf("Given number is an Even number\n");
    }
    return 0;
}

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
Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki
Page was generated in 0.1477 seconds