This blog is under construction

Sunday, 22 April 2012

Conditional operator with example

It is also called as Ternary operator "?:".  Consider the following example:

  if (a > b) {
      c = a;
  } else {
     c = b;
  }

The above statements can also be written in the following format.
  c = (a > b) ? a : b;

Ternary Operator evaluates the expression (a > b) first.  If the expression is true, then the value of 'a' will be assigned to c.  Otherwise, the value of 'b' will be assigned to 'c'.

Example program using conditional / ternary Operators:
 
  #include <stdio.h>
   int main() {
        int a, b, big;
        printf("Enter the value of a and b:");
        scanf("%d%d", &a, &b);
        big = (a > b) ? a : b;
        printf("Biggest of two numbers:%d\n", big);
        return 0;
    }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value of a and b:100 200
  Biggest of two numbers:200


No comments:

Post a Comment