In this tutorial, you shall learn about Greater-than Relational Operator in C++ programming language, its syntax, and how to use this operator with the help of examples.
C++ Greater than Operator
In C++, Greater-than Relational Operator is used to check if left operand is greater than the right operand.
The syntax to check if x
is greater than y
using Greater-than Operator is
x > y
The operator returns a boolean value of true
if x
is greater than y
, or false
if not.
Examples
1. Check if number in x is greater 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 greater than that of y
, using Greater-than Operator.
main.cpp
#include <iostream> using namespace std; int main() { int x = 5; int y = 2; if (x > y) { cout << "x is greater than y." << endl; } else { cout << "x is not greater than y." << endl; } }
Output
x is greater than y. Program ended with exit code: 0
Since value in x
is greater than that of in y
, x > y
returned true.
2. Check if string in x is greater than that of in y
Now, let us take two strings, and check if one string is greater 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 = "apple"; string y = "banana"; if (x > y) { cout << "x is greater than y." << endl; } else { cout << "x is not greater than y." << endl; } }
Output
x is not greater than y. Program ended with exit code: 0
Since value in x
is not greater than that of in y
, x > y
returned false.
Conclusion
In this C++ Tutorial, we learned about Greater-than Operator in C++, with examples.