What is Ternary Operator in C ?
It is also known as conditional operators. It requires three operands.
General Syntax :
expression1 ? expression 2: expression 3
Explanation:
Here expression 1 must be a condition. Expression 1 will always evaluated. If the condition is true then it will go to expression 2,
but the condition is false it will go for the expression 3.
Example 1:
C
C
#include<stdio.h>
int main()
{
int a, b, c, big ;
printf(“Enter three numbers : “) ;
scanf(“%d %d %d”, &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf(“\nThe biggest number is : %d”, big) ;
return 0;
}
Output
Output
Enter three numbers :
20
15
30
The biggest number is : 30
Example 2:
C
C
#include<stdio.h>
int main()
{
int a=6, b= 4,c;
c = (a>b)?b:c;
printf(“\n c = %d”,c);
return 0;
}
Output
Output
c = 6