Relational Operators in C++
Relational operators in C++ are used to compare two or more values. These operators check the relationship between values and return either true (1) or false (0).
Types of Relational Operators
C++ provides the following relational operators:
| Operator | Name | Meaning | Example |
|---|---|---|---|
== |
Equal to | Checks if two values are equal | 5 == 5 → true |
!= |
Not Equal to | Checks if two values are not equal | 5 != 3 → true |
> |
Greater than | Checks if first value is greater | 10 > 4 → true |
< |
Less than | Checks if first value is smaller | 2 < 9 → true |
>= |
Greater than or Equal to | Checks if value is greater or equal | 7 >= 7 → true |
<= |
Less than or Equal to | Checks if value is smaller or equal | 5 <= 8 → true |
Where Are Relational Operators Used?
Common Uses
- To compare marks, age, price, distance, etc.
- To validate user input (e.g., password length ≥ 8).
- To control loops (
i < nin for-loop). - To check conditions before performing an operation.
Example: Using All Relational Operators
Let us use all relational operators in a single C++ program:
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << "a == b: " << (a == b) << endl;
cout << "a != b: " << (a != b) << endl;
cout << "a > b: " << (a > b) << endl;
cout << "a < b: " << (a < b) << endl;
cout << "a >= b: " << (a >= b) << endl;
cout << "a <= b: " << (a <= b) << endl;
return 0;
}
Output:
a == b: 0
a != b: 1
a > b: 0
a < b: 1
a >= b: 0
a <= b: 1
Explanation
- a = 10, b = 20
- a == b → false (because 10 is not equal to 20)
- a != b → true
- a > b → false
- a < b → true
- a >= b → false
- a <= b → true
Using Relational Operators in if Statements
Relational operators are mostly used inside decision-making
statements like
if, else-if, and while.
These operators help the program decide which block of code to execute.
Example: Checking Eligibility
// C++ Program to check voting eligibility
#include <iostream>
using namespace std;
int main() {
int age = 17;
if (age >= 18) {
cout << "You are eligible to vote.";
} else {
cout << "You are not eligible to vote.";
}
return 0;
}
Output:
You are not eligible to vote.
Explanation
age >= 18checks whether age is 18 or more.- Since 17 is not ≥ 18, condition becomes false.
elseblock runs and prints “not eligible”.
Summary:
- Relational operators are used for comparing two values.
- They always return either 1 (true) or 0 (false).
- C++ provides six relational operators.
- These are useful in decision-making and conditions.