C Sharp: Find greater of two numbers





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

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.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s