C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result.
There are mainly 6 Comparison Operators namely:
- Greater than (>) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else returns false. example 5>3 ->returns true
- Greater than or equal to (>=) : this operator checks whether operand1 is greater than or equal to operand2. If the result turns out to be true, it returns true or else returns false. example 5>=5 ->returns true
- Less than (<) : this operator checks whether operand1 is lesser than operand2. If the result turns out to be true, it returns true or else returns false. example 3<5 ->returns true
- Less than or equal to (< =) : this operator checks whether operand1 is lesser than or equal to operand2. If the result turns out to be true, it returns true or else returns false. example 5<=5 ->returns true
- Equal to (==) : this operator checks whether operand1 is equal to operand2. If the result turns out to be true, it returns true or else returns false. example 5==5 ->returns true
- Not Equal to (! =) : this operator checks whether operand1 is not equal to operand2. If the result turns out to be true, it returns true or else returns false. example 5!=3 ->returns true
Comparison Operators have only two return values, either true (1) or False (0).
Example Code to cover all 6 Comparison Operators:
C++
// C++ Program to implement // comparison operators #include <iostream> using namespace std; int main() { int a, b; a = 5, b = 3; // example to demonstrate '>' operator if (a > b) cout << "a is greater than b" << endl; else cout << "a is not greater than b" << endl; a = 5, b = 5; // example to demonstrate '>=' operator if (a >= b) cout << "a is greater than or equal to b" << endl; else cout << "a is not greater than or equal b" << endl; a = 2, b = 3; // example to demonstrate '<' operator if (a < b) cout << "a is lesser than b" << endl; else cout << "a is not lesser than b" << endl; a = 2, b = 3; // example to demonstrate '<' operator if (a <= b) cout << "a is lesser than or equal to b" << endl; else cout << "a is not lesser than or equal to b" << endl; a = 5, b = 5; // example to demonstrate '==' operator if (a == b) cout << "a is equal to b" << endl; else cout << "a is not equal to b" << endl; a = 5, b = 3; // example to demonstrate '!=' operator if (a != b) cout << "a is not equal to b" << endl; else cout << "a is equal to b" << endl; return 0; } |
Output
a is greater than b a is greater than or equal to b a is lesser than b a is lesser than or equal to b a is equal to b a is not equal to b
Please Login to comment...