Explain ternary operator with examples.
Answers
Answer: Ternary operator is a operator which work with three operands to perform the operation.It is otherwise called as conditional operator(?:).
Syntax: (expression 1)?expression 2:expression 3;
if the expression 1 in the above statement evaluates to true, then expression 2 will be evaluated else expression 3 will be evaluated.
Example: (M>35)?P:F;
Answer:
The ternary operator is unique to c++. It is used to specify a condition with two values,and if the condition is evaluated to true, then the first value is assigned to a new variable. if the condition is evaluated to be false, then the second value is assigned to a new variable.
syntax:variable=condition? value1:value2
the following program is an example of ternary operators
#include<iostream.h>
void main()
{
clrscr();
int a=5;
int b=8;
int c;
c=(a>b)?a:b;
cout<<"the greater number is"<<c;
getch();
}
output for following program: the greater number is 8