Ternary operator with example

 In computer programming?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. Ternary means three, it means three operands are required . It is commonly referred to as the conditional operatorinline if (iif), or ternary if.

 An expression a ? b : c evaluates to b if 

the value of a is true, and otherwise to c

One can read it aloud as "if a then b otherwise c".


Let's see a simple code to understand it better :

#include<stdio.h>

#include<conio.h>

int main()
{
    int a, b,d;
    printf("Enter 2 numbers ");
    scanf("%d%d",&a,&b);
    d=a>b?a:b;
    printf("%d is greatest ",d);
    return 0;
}

 By using the above code you can get the greatest digit among 2 numbers with the help of ternary operator.  

Suppose you enter a=8 and b=5

 Now,  the condition a>b will be checked. 

If a>b is true then a will be assigned to d 

Otherwise 

b will be assigned to d

In this example as we've taken a=8 and b=5

which means a>b or 8>5

So 8 will be stored in d 

And You'll get the greatest one.

 ie:  8 is greatest 

 

Post a Comment (0)
Previous Post Next Post