Accept any two numbers, if the first number is greater than second then print the difference of these two numbers, print their sum. Write this program using ternary operator.

Ternary operator : 

we write the program first we know about ternary operator. Ternary operator are also called conditional operator (? and :) which required three expression as operands.

syntax:
TestExpression ? expression1 : expression2 ;

If test expression is true(non-zero), then expression1 is evaluated otherwise test expression is false(zero), then expression2 is evaluated.

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter the value of a and b:\n");
    scanf("%d%d",&a,&b);
    // here be use a ternary operator
    a>b?printf("difference of a and b is %d",a-b)
:printf("Sum of a and b is %d ",a+b);
    return 0;
}
Output:
Enter the value of a and b: 9 15 Sum of a and b is 24

In the above program a is less than b therefore second expression is evaluated. first it expression a>b is evaluated, it is false so the sum of the exptression2 is evaluated.

Comments

Popular posts from this blog

18 Amazing programs in C.