Relational and logical operators are used to make decisions in programs. They help the computer compare values, check conditions, and control the flow of the program. These operators are widely used in if statements, loops, and conditional expressions.
Relational Operators
Relational operators compare two values and return a Boolean result (true or false). They are essential for decision-making in programs.
Common Relational Operators
| Operator | Meaning | Example |
|---|---|---|
< | Less than | a < b |
> | Greater than | a > b |
<= | Less than or equal to | a <= b |
>= | Greater than or equal to | a >= b |
== | Equal to | a == b |
!= | Not equal to | a != b |
Using < and >
<checks if the left value is smaller than the right.>checks if the left value is greater than the right.
Explanation:
(a < b)is true because10 < 20.(a > b)is false because10is not greater than20.
Using <= and >=
<=checks if the left value is smaller or equal to the right.>=checks if the left value is greater or equal to the right.
Explanation:
Both expressions are true because
15is equal to 15.
Using == and !=
==checks if two values are equal.!=checks if two values are not equal.
Explanation:
(a == b)is false because10is not equal to20.(a != b)is true because10is not equal to20.
Examples of Relational Operators in Decision Making
Here, the relational operator
>=is used to check the eligibility condition.Output depends on the input given by the user.
Logical Operators
Logical operators are used to combine multiple conditions. They are very important in decision-making and loops.
Common Logical Operators
| Operator | Name | Description | Example |
|---|---|---|---|
&& | AND | True if both conditions are true | (a > 0 && b > 0) |
| ` | ` | OR | |
! | NOT | Reverses the truth value | !(a > b) |
Using AND (&&)
&&returns true only if both conditions are true.Syntax:
Example:
Output:
Here, both
a > 5andb > 15are true, so the AND operator returns true.
Using OR (||)
||returns true if at least one condition is true.Syntax:
Example:
Output:
Here,
a > 15is false butb > 0is true, so the OR operator returns true.
Using NOT (!)
!reverses the truth value.Syntax:
Example:
Output:
!isRainingbecomes false, so theelsepart executes.
Combining Logical and Relational Operators
You can combine relational and logical operators for complex conditions.
marks >= 50 && marks <= 100checks if marks are within the passing range.
Examples of Logical Operator Precedence
Precedence order in C++:
!(NOT)&&(AND)||(OR)
Explanation:
b && cis evaluated first →false && true = falseThen
a || false = true→ output is true