Relational Operators in C

In this article, we would discuss relational operators in C programming language. With the help of relational operators, we get to compare two values. Accordingly, as per the instructions specified, we get the outcome as either true/false or 1/0.

Relational operators basically helps us reach a decision. Besides, we mostly use them in loops. For example:

for (i = 1; i < 5; i++)
  {
       printf("%d ", i);
  }

where, < is a relational operator.

The test expressions indicates that for loop will run till value of variable i is less than 5. Here, < compares the left operand i.e. i with the right operand i.e. 5

There are mainly six types of relational operators in C programming language. We will discuss each of those in next section using relevant examples.

Relational Operators in C

Operator I.

< if the left operand is less than the right operand If it comes out to be so, then it returns with the value either true or 1.

Operator II.

> if the left operand is greater than the right operand. Returns value true or 1 if the condition satisfies.

Operator III.

<= if the left operand is less than or equal to the right operand. If it comes out to be so, then it returns with the value either true or 1.

Operator IV.

>= if the left operand is greater than or equal to the right operand. Returns value true or 1 if the condition satisfies.

Operator V.

== to check if the left operand is equal to right operand. Note: This is different from = (assignment operator) which is used to assign a variable.

Operator VI.

!= to check if the left operand is not equal to right operand. Returns value true or 1 if the condition satisfies.

Now, we will illustrate the above with the help of a program.

// Relational operators
#include <stdio.h>
int main()
{
   int a = 100, b = 25;

   printf("Value of A is 100 and B is 25 \n");
   printf("Whether A is less than B: %d \n", a < b);
   printf("Whether A is greater than B: %d \n", a > b);
   printf("Whether A is less than equal to B: %d \n", a <= b);
   printf("Whether A is greater than equal to B: %d \n", a >= b);
   printf("Whether A is equal to B: %d \n", a == b);
   printf("Whether A is not equal to B: %d \n", a != b);
}

We get the following output after compiling and executing the above code:

Value of A is 100 and B is 25
Whether A is less than B: 0
Whether A is greater than B: 1
Whether A is less than equal to B: 0
Whether A is greater than equal to B: 1
Whether A is equal to B: 0
Whether A is not equal to B: 1

If the condition is true then it provides the value 1. Otherwise, it returns with 0.

In conclusion, we have discussed relational operators in C.

Addtional Info –

To the compile the above program, we saved the file as – relational.c

And, then used the following in the terminal –

gcc -o relational relational.c

where, -o places the output of file relational.c to relational

Lastly, to execute the output file –

./relational

Similar Posts