Logical Operators Examples in C++
In C++, logical operators are used to combine multiple conditions or expressions and return a Boolean value (true or false) based on whether the combined condition is true or false. C++ provides the following logical operators:
- Logical AND (&&): Returns true if both conditions on the left and right sides of the operator are true, otherwise returns false.
- Logical OR (||): Returns true if either of the conditions on the left and right sides of the operator is true, otherwise returns false.
- Logical NOT (!): Returns true if the condition or expression following the operator is false, otherwise returns false.
Logical operators can be used with Boolean expressions or with expressions that evaluate to Boolean values. These operators are used to build complex conditions in programming and are often used in conditional statements and loops to control program flow.
The program is written in C++, which demonstrates the usage of logical operators. Here is a step-by-step explanation of the program:
- The program starts by including the input/output library iostream.
- The program declares three integer variables a, b, and c and initializes a and b to 10 and 40 respectively.
- The program uses the if statement to check if the logical AND operation between a and b is true. Since both a and b are non-zero integers, the condition evaluates to true and the program prints "1st - Condition is true" on the console.
- The program uses the if statement to check if the logical OR operation between a and b is true. Since at least one of the variables (b) is non-zero, the condition evaluates to true and the program prints "2nd - Condition is true" on the console.
- The program sets the value of a to 0 and b to 10.
- The program uses the if statement to check if the logical AND operation between a and b is true. Since a is 0, the condition evaluates to false and the program prints "3rd - Condition is not true" on the console.
- The program uses the if statement to check if the logical NOT operation on the result of a logical AND operation between a and b is true. Since a is 0 and the logical AND operation between a and b is false, the NOT operation evaluates to true and the program prints "5th - Condition is true" on the console.
- The program ends by returning 0.
Source Code
#include <iostream>
using namespace std;
int main()
{
int a=10,b=40,c;
if(a && b)
{
cout<<"1st - Condition is true"<<endl ;
}
if(a||b)
{
cout<<"\n2nd - Condition is true"<<endl ;
}
a=0;
b=10;
if(a&&b)
{
cout <<"\n3rd - Condition is true"<<endl ;
}
else
{
cout <<"\n3rd - Condition is not true"<< endl ;
}
if(!(a&&b))
{
cout <<"\n5th - Condition is true"<< endl ;
}
return 0;
}
To download raw file
Click Here
Output
1st - Condition is true
2nd - Condition is true
3rd - Condition is not true
5th - Condition is true