I saw the following code in one website to check odd or even number without using "if". But, I am not able to understand the coding and how it works. Please, can you explain the functional part of the code.
#include<stdio.h>
#include<conio.h>
int main()
{
int no;
clrscr();
printf("Enter a number");
scanf("%d",&no);
(no & 1 && printf("odd")) || printf("even");
return 0;
getch();
}
no & 1
gets the least significant bit of no
. Thus, no & 1
gets 1 if no
is odd.
If no & 1 == 0
, then the right hand side of &&
is skipped, (no & 1 && printf("odd"))
is evaluated as FALSE, and printf("even")
is evaluated.
If no & 1 != 0
, then the right hand side of &&
is evaluated and prints "odd"
on console. (no & 1 && printf("odd"))
is evaluated as TRUE if the printf()
successes, and then the right hand side of ||
is skipped.
&
is used for bit-wise AND and &&
is used for logical AND.
Now the logic is that a number is even if its least significant bit is 0
and is odd if LSB is 1
.(no & 1)
checks whether LSB is 0
or 1
, i.e, by anding it will give 0
if LSB is 0
and 1
if LSB is 1
.
If it is 0
then the right expression of &&
is not evaluated because of the short circuit behavior of the operator and hence right sub-expression of ||
prints "even"
. If no & 1
is 1
then right sub-expression of &&
is evaluated and prints "odd"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With