Conditional operator in C
Conditional operator is also known as ternary operator.
This operator is known as ternary operator because it has three operands.
Ternary operator is represented as ?: .
It is used to check a condition and depending upon the condition, particular instruction is executed by the compiler.
Condition? Block1: Block2;
Condition is any relational or logical expression. Which will be checked to see which block of statements should be executed.
Block1 refers to C language statement which will be executed if condition is true.
Block2 refers to C language statement which will be executed if condition is false.
|Program to demonstrate the use of conditional operator|
In the above program, expression c=a>b?a:b is evaluated.
Variable a contains 15 and b contains 5
Condition a>b is true, so statement after question mark (?) will be evaluated and c will contain value of a i.e. 15.
Program to find largest among two numbers using conditional operator.
printf(“\nEnter value of a=”);
printf(“\nEnter value of b=”);
|Enter value of a=9|
Enter value of b=14
Largest value= 14
|Program to read percentage of a student. If percentage is more than 35 then PASS should be displayed otherwise FAIL should be displayed.|