find the number is even or not withought using % or / operator
How to write a prog in C to findout whether the number is even or not ?
Hi Gulraize,
If we treat this as a math problem rather than a C language problem then it means whether the number is a multiple of 2 or not. So
1. Subtract 2 from the number and check the result.
2. If the result is (1 or less than 0) then number is odd, else If the result is 0 then the number is even, else subtract 2 from the result again and keep on checking (i.e. executing step 2) until you find the answer.
No % or / used in the above example.
Now if we treat this as computer specific problem, then
odd number = even number + 1.
This simply means check whether the LSB of the number is set or not. (i.e. if((number %26amp; 1) == 1)) If any bit other than the LSB bit is set then it would add only even value to the number. You can only add 1 by setting the LSB bit.
Now create the equivalent C program yourself.
Reply:not sure about c but
its something like
if int(x/2) =(x/2) then its even
if not int(x/2)=(x/2) then its odd.
Reply:divide by two, use %
if the remainder is zero, the orig # is even
if the remainder is one, it's odd.
Reply:u can't do it without the% operator
if u want the code with the%operator, here it is
mian()
{
int n;
scanf("%d",n);
if((n%2)==0)
printf("the numbet is even);
else
printf("the number is odd or zero);
}
Reply:I don't know the exact code but divide the number and test to see if it is an integer or not. If it has decimals then it is not an integer.
Reply:Do a bitwise AND (the %26amp; operator) with 00000000001 (sorry, put in the right # of 0's) and compare the result to 1. If the number = 1, then the last bit in the number was a 1, so the number was odd; if the number = 0, then the last bit in the number was a 0, so the number was even.
In fact, since zero = false and one = nonzero = true, that gives you a logical test on the result of the %26amp; operation.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment