In this tutorial, you shall learn about Less-than or Equal-to Relational Operator in C++ programming language, its syntax, and how to use this operator with the help of examples.
C++ Less than or equal to
In C++, Less than or equal to Relational Operator is used to check if left operand is less than or equal to the second operand.
The syntax to check if x
is less than or equal to y
is
x <= y
The operator returns a boolean value of true
if x
is less than or equal to y
, or false
if not.
Examples
1. Check if number in x is less than or equal to that of in y
In the following example, we take two integer values in x
and y
, and check if the value in x
is less than or equal to that of in y
, using Less than or equal to Operator.
main.cpp
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 9;
if (x <= y) {
cout << "x is less than or equal to y." << endl;
} else {
cout << "x is not less than or equal to y." << endl;
}
}
Output
x is less than or equal to y.
Program ended with exit code: 0
Since value in x
is less than or equal to that of in y
, x <= y
returned true
.
2. Check if string in x is less than or equal to that of in y
Now, let us take two strings, and check if one string is less than or equal to the other. By default, strings are compared lexicographically.
main.cpp
#include <iostream>
using namespace std;
int main() {
string x = "mango";
string y = "banana";
if (x <= y) {
cout << "x is less than or equal to y." << endl;
} else {
cout << "x is not less than or equal to y." << endl;
}
}
Output
x is not less than or equal to y.
Program ended with exit code: 0
Since value in x
is not less than or equal to that of in y
, x >= y
returned false
.
Conclusion
In this C++ Tutorial, we learned about Less than or equal to Operator in C++, with examples.