Thursday, July 30, 2009

Problem in C programming...?

How can you check whether a given number is even or odd without using if,if-else,loops,conditional operator or any type of conditions...

Problem in C programming...?
main(){


char a[2][5];


char a[0]="Even";


char a[1]="Odd";


int n,c;


scanf("%d",n);


c=n%2;


printf("the number %d is %s", %26amp;n, a);


}
Reply:Well, I can't answer this question in C code (I'm not a programmer). But if you divide by 2 and check the remainder, that gives you what you are looking for. If the remainder is 1, it's odd. If the remainder is 0, it's even.





I think there is a C function that does this, called modulus or something..?
Reply:Use the modulus operator %.





x % y produces the remainder when x is divided by y, and thus is zero when y divides x exactly.





So, in order to find out whether a number is odd or even, simply inspect the result of the of a modulus operation where the divisor equals 2. If the result is 0, then x is an even number; else, x is an odd number.





result = 23 % 2


result = 22 % 2





Note: The % operator cannot be applied to float or double.


______________
Reply:Given that a non-zero number is true, and a 0 is false, run the bitwise AND on the number:





odd = (Number %26amp; 1);





-This checks if the smallest bit is set, which is equal to 1. All odd numbers will have this bit set.





Therefore, if Number is odd, the operation will return 1, and if Number is even, it will return 0;


No comments:

Post a Comment