In this tutorial, we are going to explore the concept of logical operators in C++. The logical operators are used to check whether an expression is true, or false. Again here, if the expression is true, we get 1, and if the expression is false, we get 0. Let’s have a look at some of the logical operator symbols that we have here.
Logical operators in CPP
Operator | Description | Example |
---|---|---|
&& | This is a logical AND operator. The condition becomes true if all the operands(values) are non-zero. | a&&b |
|| | This is the logical OR operator. This returns true if any operand (value) is non-zero. | a||b |
! | This is the logical NOT operator. It converts true to false and false to true. | !(5 >= 2) |
As you can see in the above table, we have listed some logical operator symbols, which we can simply use in our programs. Now, let’s have a look at a simple C++ program, in which, we will try to make use of the above-stated logical operators.
#include <iostream>
int main()
{
int a = 6, b = 2;
std::cout << “a is even and less than 10: “<< ((a %2==0) && (a<10)) << std::endl;
std::cout << “a is even or a is less than 10: “<< ((a %2==0) || (a<10)) << std::endl;
std::cout << “Logical not operator: “<< (!(a %2==0)) << std::endl;
return 0;
}
As you can see in the above program, we have tried using different logical operators, like logical AND, logical OR, and logical NOT.
Here is the output of the above program –
a is even and less than 10: 1
a is even or a is less than 10: 1
Logical not operator: 0
As you can see, 1 means true here, and 0 means false. You can use them in your programs, as and when required.
Summary
In this tutorial, we have learned about the logical operators in C++. At times, we might require to use the logical operators in our C++ programs, especially, when we would be dealing with if-else statements, at that time, when we would have multiple conditions, we would need these logical operators.
If you find this tutorial to be interesting, you can explore our other tutorials related to C++ programming language to learn more about C++ programming language. You can also explore our other courses, related to Python, Machine learning, and Data Science, through which, you can upskill yourself.
FAQs related to Logical Operators in C++
Q: What are logical operators in C++?
Ans: Using the logical operators, we can check if the expression is true or false.
Q: What are the different symbols for logical operators in C++?
Ans: Logical operator symbols in C++ include (&&, ||, !)