In this lesson, you will learn about Logical Operators in C, their usage, and examples to better understand the topic.
Logical operators in C are used to combine conditional statements. For example, if you have two variables, a and b, and want to check if both are different than null, we use the conditional operator &
if ( a == 0 && b == 0)
The table below illustrates the Logical Operator in C
Logical Operators Symbol | Operators Name | Example |
---|---|---|
&& | AND | a && b |
|| | OR | a || b |
! | Not | !a |
#include <stdio.h> int a, b, c; int main() { a = 24; b = 12; printf("a = 24"); printf("\n"); printf("b = 12"); printf("\n"); //&& if (a && b) { printf("%d && %d Both operands are true ", a, b); } else { printf("%d && %d Either operands is true ", a, b); } printf("\n"); //|| if (a || b) { printf("%d || %d Either operands is true ", a, b); } else { printf("%d || %d Both operands are false ", a, b); } printf("\n"); if (a) { printf("%d operand is true ", a); } else { printf("%d operand is not true ", a); } printf("\n"); if (!a) { printf("%d operand is true ", a); } else { printf("%d operand is not true ", a); } return 0; }
Output
a = 24 b = 12 24 && 12 Both operands are true 24 || 12 Either operands is true 24 operand is true 24 operand is not true
In the next lesson, you will learn about the Assignments Operators in C.