C logical operator

Logical Operator in C Programming

Whenever we use if statement then we can use relational operator which tells us the result of the comparison, so if we want to compare more than one conditions then we need to use logical operators. Suppose we need to execute certain block of code if and only if two conditions are satisfied then we can use Logical Operator in C Programming.

Operator Name of the Operator
&& And Operator
|| Or Operator
! Not Operator

Let us look at all logical operators with example –

int main()
    int num1 = 30;
    int num2 = 40;
    if(num1>=40 || num2>=40)
        printf("Or If Block Gets Executed");

    if(num1>=20 && num2>=20)
        printf("And If Block Gets Executed");

    if( !(num1>=40))
        printf("Not If Block Gets Executed");

Output :

Or If Block Gets Executed
And If Block Gets Executed
Not If Block Gets Executed

Explanation of the Program :

Suppose OR Operator is used inside if statement then if part will be executed if any of the condition evaluated to be true.

if(num1>=40 || num2>=40)

In the above if statement first condition is false and second condition is true , so if part will be executed.

if(num1>=20 && num2>=20)

In the above if statement both the conditions are true so if statement will be executed, AND Operator will look for truthness of first condition, If it founds the true condition then it will look for 2nd condition. If 2nd Condition founds to be true then it will look for next condition.

Logical Operator Chart :

Operator Applied Between Condition 1 Condition 2 Final Output
AND True True True
True False False
False True False
False False False
OR True True True
True False True
False True True
False False False
NOT True - False
False - True