Give the output of the following expressions:
total=(val+500>1500)?200:400;
if:- i) val = 1000; ii) val=1500; initially
Answers
Explanation:
Given, total = (val+500>1500)?200:400;
Information we get from the above:
1. Ternary operator is being used in the evaluation of variable total.
2. We know that, a ternary operator can either evaluate to true or false.
3. The condition given for evaluation is val+500>1500.
4. If the condition is true, expression 1 will be the output.
5. If the condition is false, expression 2 will be the output.
Also, ternary operator is equivalent to If-else.
variable=Expression1?Expression2:Expression3
Ternary/Conditional Operator operates similarly to that of the if-else statement as in, Expression2 is executed if Expression1 is true else, Expression3 is executed.
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Evaluation:
1) val = 1000;
total = (1000+500>1500)?200:400;
The above is false(expression 1 is false).
Therefore, output will be 400(expression 3).
2) val = 1500;
total = (1500+500>1500)?200:400;
The above is true(expression 1 is true).
Therefore, output will be 200(expression 2).
Answer:
1) 400
2) 200
total=(val+500>1500)?200:400;
variable=expression 1? expression 2:expression 3
conditional operator either evaluates to expression 2 if condition given is true or it evaluates to expression 3 if condition given is false.
i) val = 1000;
total = (1500>1500)?200:400;
evaluates to 400 as the above condition is wrong.
therefore, total=400
ii) val = 1500;
total=(2000>1500)?200:400;
conditional operator evaluates to 200 as the above condition is true.
therefore, total=200