C programming logical operators; Through this tutorial, you will learn in detail about logical operators in c programming and how to use these operators.
Note that:- Logical operators are commonly used in decision-making in C programming.
Logical Operators in C
Logical operators are used to performing logical operations of given expressions (relational expressions) or variables.
Types of Logical Operators in C
See the following table for types of logical operators in c programming:
Operator | Meaning | Example |
---|---|---|
&& | Logical AND. True only if all operands are true | If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. |
|| | Logical OR. True only if either one operand is true | If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. |
! | Logical NOT. True only if the operand is 0 | If c = 5 then, expression !(c==5) equals to 0. |
There are examples of logical operators in C. See the following example:
Example 1 – Logical Operators in C
#include<stdio.h> int main() { int a = 5, b = 10 ,ret; ret = ( (a <= b) || (a != b) ); // 5 <= 10 ==> true. 5 != 10 ==> true. So, 1 || 1 will return 1. printf("Return value of above expression is %d\n",ret); ret = ( ( a < b) && (a == b ) ); // 5 < 10 ==>true. 5 == 10 ==> false. So, 1 && 0 will return 0; printf("Return value of above expression is %d\n",ret); ret = ! ( ( a < b) && (a == b ) ); /*we have used the same expression here. And its result was 0. So !0 will be 1.*/ printf("Return value of above expression is %d\n",ret); return 0; }
Output
Return value of above expression is 1 Return value of above expression is 0 Return value of above expression is 1
Example 2 – Logical Operators in C
#include <stdio.h> int main() { int m=40,n=20; int o=20,p=30; if (m>n && m !=0) { printf("&& Operator : Both conditions are true\n"); } if (o>p || p!=20) { printf("|| Operator : Only one condition is true\n"); } if (!(m>n && m !=0)) { printf("! Operator : Both conditions are true\n"); } else { printf("! Operator : Both conditions are true. " \ "But, status is inverted as false\n"); } }
Output
&& Operator : Both conditions are true || Operator : Only one condition is true ! Operator : Both conditions are true. But, status is inverted as false
Example 3 – Logical Operators in C
// Working of logical operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10, result; result = (a == b) && (c > b); printf("(a == b) && (c > b) is %d \n", result); result = (a == b) && (c < b); printf("(a == b) && (c < b) is %d \n", result); result = (a == b) || (c < b); printf("(a == b) || (c < b) is %d \n", result); result = (a != b) || (c < b); printf("(a != b) || (c < b) is %d \n", result); result = !(a != b); printf("!(a != b) is %d \n", result); result = !(a == b); printf("!(a == b) is %d \n", result); return 0; }
Output
(a == b) && (c > b) is 1 (a == b) && (c < b) is 0 (a == b) || (c < b) is 1 (a != b) || (c < b) is 0 !(a != b) is 1 !(a == b) is 0