In this tutorial, you shall learn about Less-than Relational Operator in C++ programming language, its syntax, and how to use this operator with the help of examples.

C++ Less than Operator

In C++, Less-than Relational Operator is used to check if left operand is less than the second operand.

The syntax to check if x is less than y using Less-than Operator is

x < y

The operator returns a boolean value of true if x is less than y, or false if not.

Examples

ADVERTISEMENT

1. Check if number in x is less than 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 that of y, using Less-than Operator.

main.cpp

#include <iostream>
using namespace std;

int main() {
    int x = 1;
    int y = 5;
    
    if (x < y) {
        cout << "x is less than y." << endl;
    } else {
        cout << "x is not less than y." << endl;
    }
}

Output

x is less than y.
Program ended with exit code: 0

Since value in x is less than that of in y, x < y returned true.

2. Check if string in x is less than that of in y

Now, let us take two strings, and check if one string is less than other. By default, strings are compared lexicographically, meaning, whichever the string comes first in a dictionary, that string is lesser.

main.cpp

#include <iostream>
using namespace std;

int main() {
    string x = "mango";
    string y = "banana";
    
    if (x < y) {
        cout << "x is less than y." << endl;
    } else {
        cout << "x is not less than y." << endl;
    }
}

Output

x is not less than y.
Program ended with exit code: 0

Since value in x is not less than that of in y, x < y returned false.

Conclusion

In this C++ Tutorial, we learned about Less-than Operator in C++, with examples.