Friday, May 21, 2010

How to find the maximum number among 3 numbers (a,b,c) in Java using Ternary Operator?

Classic way:





int maxVal = ((a %26gt; b) ? ((a %26gt; c) ? a : c) : ((b %26gt; c) ? b : c));





Test this using this program, call it myprog.java :





public final class myprog


{


public static void main(String args[])


{


int a=20,b=18,c=21;


int maxVal = ((a %26gt; b) ? ((a %26gt; c) ? a : c) : ((b %26gt; c) ? b : c));





System.out.println(maxVal);


}


}





and just vary the numbers a,b,c.





So what is this doing?





First check if a%26gt;b.





If a%26gt;b then b cannot be max so only need to compare a%26gt;c.


if a%26lt;=b then a cannot be ,max so only need to compare b%26gt;c.

savage garden

No comments:

Post a Comment