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 :

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 :

Relational Operators in C++

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.

  1. AND operator (&&): This operator combines two expressions. The computed result is true only if both the expressions evaluate to true.
  2. OR operator (||): This operator also evaluates two expressions. The computed result is true if either of its two operand expressions evaluates to true.
  3. 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.

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.

Logical Operators in C++

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

Tags: ,

Leave A Response