C++ provides six relational operators to compare numbers.
Operator | Meaning |
---|---|
< | Is less than |
<= | Is less than or equal to |
== | Is equal to |
> | Is greater than |
>= | Is greater than or equal to |
!= | Is not equal to |
Comparing string Class Strings
#include <iostream>
#include <string> // string class
int main()
{//from w ww . j a v a 2 s . c om
using namespace std;
string word = "?ate";
for (char ch = 'a'; word != "mate"; ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
// cin.get();
return 0;
}
The code above generates the following result.
Comparing integers using if statements, relational operators and equality operators.
#include <iostream> // allows program to perform input and output
//from w w w.j a v a 2 s . c o m
using std::cout; // program uses cout
using std::cin; // program uses cin
using std::endl; // program uses endl
int main() {
int number1; // first integer to compare
int number2; // second integer to compare
cout << "Enter two integers to compare: "; // prompt user for data
cin >> number1 >> number2; // read two integers from user
if ( number1 == number2 )
cout << number1 << " == " << number2 << endl;
if ( number1 != number2 )
cout << number1 << " != " << number2 << endl;
if ( number1 < number2 )
cout << number1 << " < " << number2 << endl;
if ( number1 > number2 )
cout << number1 << " > " << number2 << endl;
if ( number1 <= number2 )
cout << number1 << " <= " << number2 << endl;
if ( number1 >= number2 )
cout << number1 << " >= " << number2 << endl;
}
The code above generates the following result.