Thursday, 2 May 2019

The Conditional Operator in C


Introduction
  • It involves three operands- the logical expression plus two other expressions—this operator is also referred to as the ternary operator.
  • The conditional operator evaluates to one of two expressions, depending on whether a logical expression evaluates true or false.

Syntax
Condition ? expression1 : expression2

The ? character follows the logical expression, condition. On the right of ? are two operands, expression1 and expression2, that represent choices. 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. Remember that only one, either expression1 or expression2, will be evaluated.

Example
The conditional operator can be used in place of if-else statements.

Following program find the greater number between two numbers using if-else statements.
#include<stdio.h>
int main(){
  int num1=20,num2=30;
  if(num1>num2)
     printf(“%d is greater than %d.”,num1,num2);
 else
       printf(“%d is greater than %d.”,num2,num1);

  return 0;
}
Output:
  30 is greater than 20.

Now we will find out the greater number using conditional operator.
#include<stdio.h>
int main(){
  int num1=20,num2=30;
     num1>num2?printf(“%d is greater than %d.”,num1,num2):printf(“%d is greater than %d.”,num2,num1);

  return 0;
}
Output:
  30 is greater than 20.


Please comment and share if you find it useful.

No comments:

Post a Comment