C - Operator Conditional Operator


The conditional operator is a simple version of if statement.

Because three operands are involved-the logical expression plus two other expressions-this operator is called the ternary operator.

The general representation of an expression using the conditional operator looks like this:

condition ? expression1 : expression2

The value that results from the operation will be the value of expression1 if condition evaluates to true, or the value of expression2 if condition evaluates to false.

You can use the conditional operator in a statement such as this:

x = y > 7 ? 25 : 50;

This statement results in x being set to 25 if y is greater than 7, or to 50 otherwise.

This is a nice shorthand way of producing the same effect as this:

if(y > 7)
  x = 25;
  x = 50;

The following code calculates the discount based on quantity.


#include <stdio.h>

int main(void)
  const double unit_price = 3.50;           // Unit price in dollars
  const double discount1 = 0.05;            // Discount for more than 10
  double total_price = 0.0;
  int quantity = 0;

  printf("Enter the number that you want to buy:");
  scanf(" %d", &quantity);

  total_price = quantity * unit_price * (1.0 - quantity > 10 ? discount1 : 0.5);

  printf("The price for %d is $%.2f\n", quantity, total_price);
  return 0;/*from w ww. j a  va2  s. c  om*/


Related Topics