In this video of ternary operator he is saying a%2 can also be written as a&1 how ??
Meaning of a&1?
Hello @Ramitgoel,
These two operators ‘%’ and ‘&’ are interchangeable due their common application i.e.,
To check if a number is odd or even.
Suppose, a is variable of type int.
int a;
-
‘%’ operator: it is used to obtain the remainder in the division operation:
Now, if we would divide any number with 2 then its remainder would either be 0 or 1.
1.1. For even number: remainder would be 0
example: 4%2=0
1.2. For odd number: remainder would be 1
example: 5%2=1 -
‘&’ operator: It is a bit-wise AND operator:
Now, if you would AND the number(binary representation) with 1(binary representation) the output would either be 0 or 1.
2.1. For even number: remainder would be 0
example: 4&1=0
0100 (4)
0001 (1)
0000 (Result of bit-wise AND)
2.2. For odd number: remainder would be 1
example: 5&1=1
0101 (5)
0001 (1)
0001 (Result of bit-wise AND)
Hope, this would help.
Give a like, if you are satisfied.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.