C++ Relational Operators

The C++ relational operators used to compare two numbers and check which one is larger or smaller than the other. The result is a boolean value – true or false.

Advertisements

There are four relational operators listed here.

Relational OperatorDescription
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

The relational operators are used in a C++ program where you want to check for some condition before executing a block of statement such as if-else or switch or a loop. More about branching, loops in future lessons.

The syntax for an expression with relational operator is:

(expression1) relational operator (expression2)

You can replace the expression with a constant, variable or anything comparable and the result will be either true or a false.

Example Program: Relational Operator

The following program demonstrate the use of a relational operator. The program requests four input numbers and then find the greatest number of all and prints the result to the console.

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    int a,b,c,d;
    
    
    cout << "Enter value for a:";
    cin >> a;
    
    cout << "Enter value for b:";
    cin >> b;
    
    cout << "Enter value for c:";
    cin >> c;
    
    cout << "Enter value for d:";
    cin >> d;
    
    if(a >= b)
    {
         if(c >= a)
         {
              if(d >= c)
              {
                   cout << "The greatest number is" << " " << d << endl;
              }
              else
              {
                  cout << "The greatest number is" << " " << c << endl;
              }
         }
         else 
         {
              if(d >= a)
              {
                   cout << "The greatest number is" << " " << d << endl;
              }
              else
              { 
                  cout << "The greatest number is" << " " << a << endl;
              }
         }
    }
    else
    {
        if(c >= b)
        {
             if(d >= c)
             {
                  cout << "The greatest number is" << " " << d << endl;
             }
             else
             {
                 cout << "The greatest number is" << " " << c << endl;
             }
        }
        else
        {
            if(d >= b)
            {
                 cout << "The greatest number is" << " " << d << endl;
            }
            else
            {
                cout << "The greatest number is" << " " << b << endl;
            }
        }
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

Enter value for a:45
Enter value for b:66
Enter value for c:70
Enter value for d:4
The greatest number is 70


Advertisements