Using Logical Operators in C: A Beginner's Guide


C provides three logical operators when we test more than one condition to make decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).

OperatorExampleMeaning
&& (Logical AND) expression1 && expression2 true only if both expression1 and expression2 are true
|| (Logical OR) expression1 || expression2 true if either expression1 or expression2 is true
! (Logical NOT) !expression true if expression is false and vice versa

The code is a C program that demonstrates the use of logical operators in C. Here is an explanation of each line of the code:

  • int a=32; declares a variable a of type int and assigns it the value 32.
  • printf("\nLogical And : %d",(a>=35 && a<=100)); uses the logical operator '&&' to check if the value of a is greater than or equal to 35 and less than or equal to 100, if both conditions are true then it returns 1 otherwise 0. This is printed in the console.
  • printf("\nLogical Or : %d",(a>=35 || a<=100)); uses the logical operator '||' to check if the value of a is greater than or equal to 35 or less than or equal to 100, if either of the conditions is true then it returns 1 otherwise 0. This is printed in the console.
  • printf("\nLogical Not : %d",!(a>=35)); uses the logical operator '!' to check if the value of a is not greater than or equal to 35, if true then it returns 1 otherwise 0. This is printed in the console.
  • return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.

When you run this code, it will perform logical operations on variables and print the results in the console.

Source Code

//Logical Operators
 
#include<stdio.h>
int main()
{
    int a=32; //>=35 and(&&) <=100
    printf("\nLogical And : %d",(a>=35 && a<=100));
    printf("\nLogical Or  : %d",(a>=35 || a<=100));
    printf("\nLogical Not : %d",!(a>=35));
 
 
    return 0;
}
 
To download raw file Click Here

Output

Logical And : 0
Logical Or  : 1
Logical Not : 1

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C