This blog is under construction

Sunday 22 April 2012

Comparison operators in C

Comparison operator is used to compare the first operand with the second operand and gives us the logical output(true/false).  Usually, comparison operator is used to check whether one value is less than or equal to or not equal to or greater than to another value. Using comparison operators on floating point value results in unexpected outputs.  Below are few examples for comparison operators.

Comparison operators example in C:
if (x == y) {  // checks whether value of x is equal to y (1 - true; 0 - false)
printf("x and y are equal");
}

if (x < y) { // checks whether the value of x is less than y
printf("x is less than y");
}

if (x > y) {  // checks whether the value of x is greater than y
printf("x is greater than y");
}

if (x <= y) {  // checks whether the value of x is less than or equal to y
printf("x is less than or equal to y");
}

if (x >= y) { // checks whether the value of x is greater than or equal to y
printf("x is greater than or equal to y");
}

In all the cases, the expression returns 1 if the result of the comparison is true. Otherwise, expression returns 0.

Below are various comparison operators available in c language.
 Operator Explanation
 < less than
 <= less than or equal to
 > greater than
 >= greater than or equal to
 == equal to
 != not equal to



Example C program using relational/comparison Operators:
 
  #include <stdio.h>
  int main() {
        int a = 10;
        if (a > 5)
                printf("%d is greater than 5\n", a);
        if (a >= 10)
                printf("%d is greater than or equal to 10\n", a);
        if (a < 20)
                printf("%d is less than 20\n", a);
        if (a <= 10)
                printf("%d is less than or equal to 10\n", a);
        if (a == 10)
                printf("%d is equal to 10\n", a);
        if (a != 20)
                printf("%d is not equal to 20\n", a);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  10 is greater than 5
  10 is greater than or equal to 10
  10 is less than 20
  10 is less than or equal to 10
  10 is equal to 10
  10 is not equal to 20



1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete