I want explanation for this code, please. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I want explanation for this code, please.

Int n; Scanf("%d", & n) ; If(n&0x01) { Printf("odd") ; } Else { printf("even") ; }

1st Jul 2019, 12:33 PM
David Boga
David Boga - avatar
3 Answers
+ 2
0x01 --> means 01 in hex . So, the number is : 00000001 & means bitwise operator As a result, if n=10 for example in dec we have 00000 1 10 & 00000001 -------------- --> returns 0 if n=11 for example in dec we have 00000 1 11 & 00000001 -------------- --> returns 1 So, depending on the last digit of n the output will be 1 or 0 and the decision will be odd or even. -- ================== The statement is used for performance reasons as it is much faster than n%2
1st Jul 2019, 1:01 PM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 5
that doesn't seems to be valid logic & is AND bitwise operator. so for example if n is 2 the operation is 1 0 => 2 0 1 => 1 _____& 0 0 => 0 (0 in c/c++ is false) in this case the logic is valid but, lets say the input is 3 1 1 => 3 0 1 => 1 _______& 0 1 => 1 (true, since non zero is true) the result are true, but 3 is an odd number
1st Jul 2019, 12:55 PM
Taste
Taste - avatar
+ 1
This program : - takes an input from user (integer) - test with binary operator and (&) if this number is odd or even : all odd numbers, in binary, finish by bit 1 (like 3 : 0011) and all even number finish by 0 bit (like 2 : 0010). So if number is odd, n&0x01 is 1, else, it is 0.
1st Jul 2019, 12:50 PM
Théophile
Théophile - avatar