Logical Operators in C Programming Language

Rumman Ansari   Software Engineer   2019-03-31   11433 Share
☰ Table of Contents

Table of Content:


C language supports following 3 logical operators. Following table shows all the logical operators supported by C language.

Operator Description Example
&& (logical and)  If both the operands are non-zero, then the condition becomes true. (0 && 1) is false
|| (logical or)  If any of the two operands are non-zero, then the condition becomes true. (0 || 1) is true
(logical not) Logical NOT Operator Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(0 && 1) is true

Logical AND Operator

Try the following example to understand the logical operators in C

Program

#include
void main() {
	int p = 0;
	int q = 1; 
	printf("p && q = %d \n",(p&&q)); 
	 
 }

Output

p && q = 0
Press any key to continue . . .

Logical OR Operator

Try the following example to understand the logical operators in C

Program

#include
void main() {
	int p = 0;
	int q = 1; 
	printf("p && q = %d \n",(p||q)); 
	 
 }

Output

p && q = 1
Press any key to continue . . .

Logical NOT Operator

Program

Try the following example to understand the logical operators in C

#include
void main() {
	int p = 0; 
	printf("!p= %d \n",(!p)); 
	 
 }

Output

!p= 1
Press any key to continue . . .

Logical Operators Example

Program

Try the following example to understand the logical operators available in C

// C Program to demonstrate the working of logical operators

#include
int main()
{
    int a = 10, b = 10, c = 20, result;

    result = (a == b) && (c > b);
    printf("(a == b) && (c > b) equals to %d \n", result);

    result = (a == b) && (c < b);
    printf("(a == b) && (c < b) equals to %d \n", result);

    result = (a == b) || (c < b);
    printf("(a == b) || (c < b) equals to %d \n", result);

    result = (a != b) || (c < b);
    printf("(a != b) || (c < b) equals to %d \n", result);

    result = !(a != b);
    printf("!(a == b) equals to %d \n", result);

    result = !(a == b);
    printf("!(a == b) equals to %d \n", result);

    return 0;
}

Output

(a == b) && (c > b) equals to 1
(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a == b) equals to 1
!(a == b) equals to 0
Press any key to continue . . .

Explanation of logical operator program

  • (a == b) && (c > 10) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).