Comparison Operators
Part of the Fundamentals section of Coddy's C++ journey — lesson 21 of 74.
Comparison operators are used to compare between two operands.
Sometimes we need to check whether an operand is bigger/smaller/... than another operand. The following table shows possible operators for comparison:
| Operator | Meaning | Example |
|---|---|---|
| == | Equal | 1 == 2 returns false |
| != | Not Equal | 1 != 2 returns true |
| > | Greater Than | 1 > 2 returns false |
| < | Lower Than | 1 < 2 returns true |
| >= | Greater or Equal | 1 >= 2 returns false |
| <= | Lower or Equal | 1 <= 2 returns true |
The comparison operator returns true if the comparison is correct or false otherwise.
For example:
int var1 = 13;
int var2 = 12;
bool var3 = var1 != var2;var3 will hold true because var1 and var2 are not equal
Remember the
booltype,var3is a bool.
Challenge
BeginnerWrite a script that initializes 2 variables n1 and n2 with the values 8 and 9 (accordingly).
After that initialize another variable n3 that will hold whether n1 is bigger than n2.
Try it yourself
#include <iostream>
int main() {
// Type your code below
// Don't change the line below
std::cout << "n1 = " << n1 << ", n2 = " << n2 << ", n3 = " << n3 << std::endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else