C Tutorial C References

C - comparison operators example



The example below illustrates the usage of C comparison operators: ==, !=, >, <, >=, <=.

#include <stdio.h>
 
int main (){
  printf("10 == 10: %d\n", (10 == 10));
  printf("10 != 10: %d\n", (10 != 10));
  printf("10 < 20: %d\n", (10 < 20));
  printf("10 > 20: %d\n", (10 > 20));
  printf("10 <= 20: %d\n", (10 <= 20));
  printf("10 >= 20: %d\n", (10 >= 20));
  return 0;
}

The output of the above code will be:

10 == 10: 1
10 != 10: 0
10 < 20: 1
10 > 20: 0
10 <= 20: 1
10 >= 20: 0

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

#include <stdio.h>
 
void range_func(int x){
  //&& operator is used to combine conditions
  //returns true only when x >= 10 and x <= 25
  if(x >= 10 && x <= 25)
    printf("%d belongs to range [10, 25].\n", x); 
  else
    printf("%d do not belongs to range [10, 25].\n", x);
}

int main (){
  range_func(15);
  range_func(25);
  range_func(50);
  return 0;
}

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ C - Operators