Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use in & and && operator in the following program?

Tags:

c

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();
}
like image 593
kalyan Avatar asked Dec 02 '22 17:12

kalyan


2 Answers

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.

like image 160
timrau Avatar answered Dec 16 '22 01:12

timrau


& 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".

like image 41
haccks Avatar answered Dec 16 '22 00:12

haccks