C - Use tenary operator to get larger value

Description

Use tenary operator to get larger value

Demo

#include <stdio.h> 

int main() /*from  w  ww. j  a v a  2  s  .c  om*/
{ 
    int a,b,larger; 

    printf("Enter value A: "); 
    scanf("%d",&a); 
    printf("Enter different value B: "); 
    scanf("%d",&b); 

    larger = (a > b) ? a : b; 
    printf("Value %d is larger.\n",larger); 
    return(0); 
}

Result

?: is known as a ternary operator: It's composed of three parts.

It's a comparison and then two parts: value-if-true and value-if-false.

The statement looks like this:

result = comparison ? if_true : if_false; 

The statement begins with a comparison.

Any comparison from an if statement works, as do all operators, mathematical and logical.

When comparison is true, the if_true portion of the statement is evaluated and that value stored in the result variable.

Otherwise, the if_false solution is stored.

Related Topic