In this lesson, we will learn about the various relational and logical operators in c++ and how they are used in forming expressions. One thing common to both these operators is that they evaluate to either a true or a false value. A true value is denoted by 1 and a false value is denoted by 0 in C++.

## 1. Relational Operators

Let’s begin with relational operators. They are used to determine the relation between different operands. C++ has these six relational or comparison operators : <, <=, ==, >, >=, !=

A relational expression is evaluated to true if the comparison is true else it evaluates to false. Another point about these operators is that they do not work on strings!

The following program illustrates the use of the relational operators :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//Program to illustrate relational operators #include<iostream> #include<conio.h> using namespace std; int main() { int num1 = 4; int num2 = 7; cout << "num1 > num2 "<< (num1>num2) <<endl ; cout << "num1 < num2 "<< (num1<num2) <<endl; cout << "num1==num2 " << (num1==num2) <<endl; getch(); return 0; } /* output num1 > num2 0 num1 < num2 1 num1==num2 0 */ |

In this program, each relational expression such as (num1>num2) is computed which gives value 1 (true) or 0 (false).

Here is a live preview of the program :

## 2. Logical Operators

Now let’s learn about logical operators. C++ provides three such operators : AND operator (&&), OR operator (||) and NOT operator (!) . && and || are binary operators whereas ! is a unary operator.

- AND operator (&&): This operator combines two expressions. The computed result is true
*only if*both the expressions evaluate to true. - OR operator (||): This operator also evaluates two expressions. The computed result is true if
*either of*its two operand expressions evaluates to true. - NOT operator (!): This is a unary operator that negates its operand. That is, if an expression is true, it becomes false and vice-versa.

The following program illustrates the use of the logical operators.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream> #include<conio.h> using namespace std; int main() { int a = 4; int b = 5; int c = 6; int d = 7; cout << "a<b && c<d : " << (a<b && c<d) << endl; cout << "a>b || c<d : " << (a<b || c<d) << endl; cout << "!( a<b ) : " << !(a<b && c<d) << endl; getch(); return 0; } /* OUTPUT a<b && c<d : 1 a>b || c<d : 1 !( a<b ) : 0 */ |

In this program, the expression containing && evaluates to 1 as both its operands evaluate to 1. In the expression containing ||, first expression (a>b) evaluates to 0 but the second evaluates to 1 so the result is 1. The third expression containing! simply negates the result of a<b to 0 from 1.

Here is the live preview.

Hope you are clear with this topic. Do let us know your queries. Drop your comments below.