Comparison operators are symbols or combinations of symbols that allow us to compare two values and determine if a certain condition is true or false.
These operators are widely used in control structures such as conditionals and loops to make decisions based on value comparisons.
The most common comparison operators are,
Operator | Example | Result |
---|---|---|
Equal (==) | 5 == 5 | true |
Not equal (!=) | 3 != 7 | true |
Greater than (>) | 10 > 5 | true |
Less than (<) | 2 < 8 | true |
Greater than or equal (>=) | 7 >= 7 | true |
Less than or equal (<=) | 4 <= 4 | true |
As we have said, these operators return a boolean value (true
or false
) depending on the result of the comparison.
- Equal
==
: compares if two values are equal. - Not equal
!=
: compares if two values are different. - Greater than
>
: compares if the value on the left is greater than the value on the right. - Less than
<
: compares if the value on the left is less than the value on the right. - Greater than or equal to
>=
: compares if the value on the left is greater than or equal to the value on the right. - Less than or equal to
<=
: compares if the value on the left is less than or equal to the value on the right.
Use of comparison operators in programming languages
The use of operators is basically the same in all programming languages. Next, we will see how to use comparison operators in different programming languages:
For example, this would be the case in C, C++, C# or Java
int a = 5;
int b = 10;
bool equal = (a == b); // equal = false
bool notEqual = (a != b); // notEqual = true
bool greaterThan = (a > b); // greaterThan = false
bool lessThan = (a < b); // lessThan = true
bool greaterOrEqual = (a >= b); // greaterOrEqual = false
bool lessOrEqual = (a <= b); // lessOrEqual = true
It would be very similar in the case of JavaScript, with the exception of declaring the variable with let
let a = 5;
let b = 10;
let equal = (a == b); // equal = false
let notEqual = (a != b); // notEqual = true
let greaterThan = (a > b); // greaterThan = false
let lessThan = (a < b); // lessThan = true
let greaterOrEqual = (a >= b); // greaterOrEqual = false
let lessOrEqual = (a <= b); // lessOrEqual = true
Similarly in Python
a = 5
b = 10
equal = (a == b) # equal = False
notEqual = (a != b) # notEqual = True
greaterThan = (a > b) # greaterThan = False
lessThan = (a < b) # lessThan = True
greaterOrEqual = (a >= b) # greaterOrEqual = False
lessOrEqual = (a <= b) # lessOrEqual = True
In the examples,
- We have declared two integer variables
a
andb
- Then, we use the comparison operators to compare the values of the variables
- We store the result in boolean variables