C Programming Tutorial – Logical Operators

C programming language has logical operators for logical expressions. The output of a logical operation is a Boolean value – true or false. In a logical expression you have one or more operands and each has a truth value, depending on the truth value of each operand the logical operator decides the final truth value of the logical expression.

Logical Operators

A list of logical operators in C language is given below. The minimum numbers of operands required by each of the operators is also given in the same table.

  1. AND (&&)
  2. OR (||)
  3. NOT (!)

We shall discuss each of them in more detail now.

AND (&&) operator

The AND operation is denoted by two ‘ampersand’ symbol. To understand the AND operation, consider the following expression,

A && B
Where A = (3 < 4) and B = (10 < 20)

The final output of the expression depends on following conditions.

A is true && B is true = A && B is true

A is false && B is true = A && B is false.

A is true && B is false = A && B is false.

A is false && B is false = A && B is false.

So, the AND is only true when both A and B are true.

OR (||) operator

The OR operation is also useful logical operator in C language. The value of expression is true under following conditions.

A is true || B is true = A || B is true

A is false || B is true = A || B is  true

A is true || B is false = A || B is true

A is false || B is false = A || B is false

From the above example, it is clear that the OR is only true when at least A or B is true.

NOT (!) operator

The NOT is called the negation operation. It negates the truth value of the existing expression.

For example,

if A is true , then !A is false

If A is false, then !A is true.

Note:- The !(!A) == A.

Example – AND, OR, NOT

/* C Program to demonstrate use of Logical Operators */
#include <stdio.h>

int main() {
    int A, B ;
    A = (5 < 10); /* True */
    B = (10 < 20); /* True */
    printf("\n\n\n\n\n");

/* Working of AND operation - both A and B must be true */

    if(A && B) {

    printf("\tOutput AND - both A and B are true\n\n");

    }

/* Operation of Not operator */

    A = (2 < 10); /* False */
    B = (4 < 8); /* True */

/* A && B is False */

    if(!(A && B)) {

    printf("\tOutput NOT - (A && B) is False so negation !(A && B) is True\n\n");

    }

/* Working of OR operator - any one of A or B must be true */

    if (A || B) {

    printf("\tOutput OR - Any one of A or B is true\n\n");

    }

getch();
return 0;

}

Output – AND, OR, NOT

Output - Logical Operators
Output – Logical Operators

Bibliography

Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.

Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.

Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.

 

Advertisements