C Programming Interview / Viva Q&A: 3 (Logical Operator)

In this C program we’ve 2 operands and one AND operator(&&). We use Logical NOT Operator to change the true and false conditions inside if statement. Check the source code below and guess the output.

Related Read:
Logical Operators In C

Logical && Operator in C Program

 
#include < stdio.h >

int main()
{
    int a = 20, b = 30;

    if( a && b )
    {
        printf("a = %d\n", a);
    }
    else
    {
        printf("b = %d\n", b);
    }
    return 0;
}

Output:
a = 20

In above C program, a = 20 and b = 30. In C, any non-zero number is considered as true. So the condition is if statement returns true and the block of code inside if statement gets executed.

Whats the output of this C Program?

 
#include < stdio.h >

int main()
{
    int a = 20, b = 30;

    if(  !(!a) && a  )
    {
        printf("a = %d\n", a);
    }
    else
    {
        printf("b = %d\n", b);
    }
    return 0;
}

Lets evaluate the if condition in above c source code. a = 20, which is non-zero number, so its considered as true(1). So negating the true(1) value !a gives false(0). Negating that false(0) value !(!a) gives true(1).

So !(!a) returns true(1). So both sides of &&(AND) is true, so the whole thing returns true. So the block of code inside if condition gets executed.

Output:
a = 20

C Programming Interview / Viva Q&A: 3 (Logical Operator)



YouTube Link: https://www.youtube.com/watch?v=JxPB_JxNyHY [Watch the Video In Full Screen.]


Important:
1. Logical &&(AND) Operator returns true when both sides operands have true(non-zero number) value. In any other case it returns false(0) value.
2. Any non-zero number is considered as true and zero(0) is considered as false in C programming language.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert