Logical Operators are used mainly between two conditions. It checks whether both operands are True(1 or Non-zero) or False(Zero).
In C Programming 3 logical operators are highly used. Those are
- && AND Operator returns true if both sides are non-zero.
- || OR Operator returns true if any of the sides is non-zero.
- ! NOT Operator returns the reverse value of the result; if the result is true then it will return false and vice versa.
&& AND Operator
if(Operand1 && Operand2) {
//true
}
else{
//false
}
|| OR Operator
if(Operand1 || Operand2) {
//true
}
else{
//false
}
! NOT Operator
if(!Operand) {
//true
}
else{
//false
}
Let's code
#include<stdio.h>
int main(){
//Change the numbers with 1 and 0 and see the output
also change it signed integer and integer values other than 1
if(1 && 0)
{
printf("True\n");
}
else{
printf("False\n");
}
if(1 || 0)
{
printf("True\n");
}
else{
printf("False\n");
}
if(!(1))
{
printf("True\n");
}
else{
printf("False\n");
}
}
Let's take another example. Here we will take inputs from the user and check some conditions and compare if the statement satisfies or not.
#include<stdio.h>
int main(){
int num1,num2;
printf("Enter 1st Number:");
scanf("%d",&num1);
printf("Enter 2nd Number:");
scanf("%d",&num2);
if(num1>num2 && num1==num2)
{
printf("True\n");
}
else{
printf("False\n");
}
if(num1>num2 || num1<num2)
{
printf("True\n");
}
else{
printf("False\n");
}
if(!(num1>num2))
{
printf("True\n");
}
else{
printf("False\n");
}
}
Change the inputs and operators to see different outputs and try to understand what it returns.