C# Programming - Operators - Discussion

Discussion Forum : Operators - General Questions (Q.No. 17)
17.
What will be the output of the C#.NET code snippet given below?
int a = 10, b = 20, c = 30; 
int res = a < b ? a < c ? c : a : b; 
Console.WriteLine(res);
10
20
30
Compile Error / Syntax Error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
15 comments Page 2 of 2.

NguyenNam said:   1 decade ago
if (10<20)
{
if( 10<30)
{
return c= 20
}
else
return a= 10
}
else
{
return b=20
}

Navya said:   1 decade ago
It is like only inner If-Else statements.
Like this:

a=10, b=20, c=30;
if(a<b) //10<20 is true
{
if(a<c) //10<30 is true
res=c; //30
else
res=a //10
}
else
res=b //20

--Initially check the condition a<b if it is true loop will go on, if condition fails result will be 20.

--If condition a<b true then again check the condition a<c.

--If condition a<c is true print result as 30 otherwise result will be 20.
So our answer is 30.

Nivas said:   1 decade ago
What mean by : ? please explain. Am confused.

Krishna said:   10 years ago
This problem solution based on operator precedence, lets show them below how it is evaluate. Here two operators are presented one is Relational (<) and another one is Conditional (?:).

In this two operators relational operator having highest priority so it evaluate like this:

10<20?20<30?30:10:20.

In above condition 10<20 is TRUE. So 20<30?30:20. Here is also condition true answer is 30.

Ahmed said:   10 years ago
a < b ? a < c ? c : a : b;

Make two separate condition,
a < b ? (a < c ? c : a) : b;

Value of a = 10, b= 20, c=30.

Step 1 :- a < b means (10 < 20) then Ans b = 20.

Now it will check for inner condition,
Step 2: - (a < c ? c : a) means (10 < 30) then Ans c = 30.

Now it will compare both inner and outer values,

Step 3 : - From outer we got b = 20 and from inner we got c =30.
(20 ? (30) c:b).

Now it will check which one is greater,

Step 4 : - here b < c means (20 < 30) then Ans c = 30.
(1)


Post your comments here:

Your comments will be displayed after verification.