C Sharp: Find greater of two numbers


c-sharp

 

 


Assumption:

int num1 =double.Parse(Console.ReadLine());
int num2 = double.Parse(Console.ReadLine());

Supplied numbers are not equal.

Way 1:(Using Relational operator)

if (num1 > num2)
    Console.WriteLine("Max is:{0}", num1);
else
    Console.WriteLine("Max is:{0}", num2);

Way 2:(Using Conditional operator)

Console.WriteLine("Max is:{0}", num1>num2?num1:num2);

Way 3:(Using Math.Max())

Console.WriteLine("Max is:{0}", Math.Max(num1,num2));

Way 4:(Using Math.Abs())

Console.WriteLine("Max is:{0}", ((num1+num2)+Math.Abs(num1-num2))/2);

Analysis:
Among these ways I don’t think the first three solutions need any explaination. But what we will anayse here is the Way 4. The half of the summation of sum of two numbers and their absolute difference results the greater of the two. Similarly we can get the lower among them as the half of the substraction between the sum of the two numbers and their absolute difference.
Ex:

Console.WriteLine("Min is:{0}", ((num1+num2)-Math.Abs(num1-num2))/2);
Advertisements