Relational Operators


We often compare the two quantities and make certain decisions based on their relationship. For example, we can compare the ages of two people or the prices of two items and others. These comparisons can be made with the help of relational operators. Such an expression

20 > 10 or x < y

containing a relational operator is termed as a relational expression. The value of a relational expression is either one or zero. It is one of the specified relations is true and zero if the relation is false. For example

20 > 10 // true
20 < 10 // false 

C supports a total of six relational operators. These operators and their meanings are displayed in the table.

Relational Operators

Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Relational expressions are used in decision statements, such as if and while, to determine the activity of a running program. We have already used the while statement in the next tutorial.

Program
// Relational Operators
#include <stdio.h>

int main() 
{
  int a = 20, b = 10;
  printf("Two numbers are (a,b) = %d %d \n",a,b);
  if(a > b)
   printf("a is greater than b\n");
  if(a < b)
   printf("a is less than b\n");
  if(a >= b)
   printf("a is greater than or equal to b\n");
  if(a <= b)
   printf("a is less than or equal to b\n");
  if(a == b)
   printf("a is equal to b\n");
  if(a != b)
   printf("a is not equal to b\n");
  return 0;
}

In the example above, the output will be printed as soon as the true value is found in the if statements. So three outputs have been printed. I will learn more about this statement in more details in later tutorials.


Program
// Relational Operators using while statment
#include <stdio.h>

int main() 
{
  int a = 5;
  while(a != 0)
  {
   printf("a = %d\n",a);
   --a;
  }
  return 0;
}

In the example above, the loop will run until the value of a is 0 and the value of a will be printed, and below (--a) means that the value of a will decrease by 1 every time the while loop runs, it is called decrement operators. See the following tutorials for details on this.