Relational operators in an expression : C Programming



In this tutorial we are going to see how we can use relational operators in an expression.

Relational operators in an expression

First of all we are going to list out the different relational operators.


Operator,Name of Operator
>,Greater Than
<,Less Than >=,Greater than Operator
<=,Less than Operator ==,Comparison Operator !=,Not equal to Operator [/table]

Use of relational operators in an expression is nothing but using if statement in an expression indirectly

Reading expression containing relational operators

If we use any of the operator listed in above table in your expression then that part of expression will provide you either 0 or 1 as a result. Consider below example –

res = 100 > 20

above expression will assign value 1 to a variable res because relational operators in an expression is used. Consider below example –

Thumb rules for solving expression

Keep in mind simple 2 thumb rules when you find relational operators in an expression –

  1. Check whether the expression is true or false. If expression is true then simply replace the expression with 1
  2. If expression results into false statement then replace the expression with 0

Examples

Example #1 : Usage of relational operator

#include <stdio.h>
int main(int argc, char *argv[]) {

   int num1 = 100;
   int num2 = 100;

   printf("%d",num1 >  num2);
   printf("%d",num1 >= num2);
   printf("%d",num1 <= num2);
   printf("%d",num1 <  num2);

   return 0;
}

Output :

0 1 1 0

You can see, we have used the relational operators inside the expression and it returns the result with values either 0 or 1. Operation is similar to below statement –

if(num1 > num2)
   printf("1");
else
   printf("0");

Example #2 : Indirect use of if statement

#include<stdio.h>
void main()
{
  int num1 = 100,num2=200,num3;
  num3 = ( num1 >= 100 ) + (num2 < 50 );
  printf("%d",num3);
}

Output :

1

Explanation :

Consider this statement –

num3 = ( num1 >= 100 );

above statement can be written in following way –

if( num1 >= 100 )    
   num3 = 1;
else    
   num3 = 0;

considering above thumb rules we can calculate the value of num3 as –

num3 = ( num1 >= 100 ) + (num2 < 50 );
num3 = 1 + (num2 < 50 );  // ( num1 >= 100 ) is True
num3 = 1 + 0;             // ( num2 <  50  ) is False
num3 = 1;