Find Greater of Two Numbers

Assumptions:

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

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

 

and 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 analyse 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);

Ebook Download
View all
Learn
View all