3
Answers

Ternary Operator

Photo of Maha

Maha

11y
911
1
What one can learn from ternary operator? Because in1>n2 and n1<n2 are giving different output. An example program is given. Problem is highlighted.

using System;
class Program
{
static void Main(string[] args)
{
int n1, n2;
n1 = 10;
n2 = 20;

int max = (n1 > n2) ? n1 : n2;
Console.WriteLine(max);//20

int min = (n1 < n2) ? n1 : n2;
Console.WriteLine(min);//10

Console.ReadKey();
}
}

Answers (3)

0
Photo of Maha
NA 0 173.6k 10y
Thank you for your explanation brothers.
0
Photo of Abhay Shanker
NA 10.5k 2.4m 11y
The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs.

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

The condition must evaluate to true or false. If condition is truefirst_expression is evaluated and becomes the result. If condition is falsesecond_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
0
Photo of Vulpes
NA 98.3k 1.5m 11y
The ternary operator takes this general form:

a ? b : c

where 'a' is a bool expression and 'b' and 'c' are expessions of the same type.

If 'a' is true, the value is 'b'.

If 'a' is false, the value is 'c'.


In the first example:

int max = (n1 > n2) ? n1 : n2;

10 > 20 is false and so the value is n2 which is 20.

In the second example:

int min = (n1 < n2) ? n1 : n2;

10 < 20 is true and so the value is n1 which is 10.