Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method that returns greater value of two numbers

Tags:

methods

c#

So I have this code

  static void Main(string[] args)
    {
        Console.Write("First Number = ");
        int first = int.Parse(Console.ReadLine());

        Console.Write("Second Number = ");
        int second = int.Parse(Console.ReadLine());

        Console.WriteLine("Greatest of two: " + GetMax(first, second));
    }

    public static int GetMax(int first, int second)
    {
        if (first > second)
        {
            return first;
        }

        else if (first < second)
        {
            return second;
        }
        else
        {
            // ??????
        }
    }

is there a way to make GetMax return a string with error message or something when first == second.

like image 720
Martin Dzhonov Avatar asked Sep 28 '13 18:09

Martin Dzhonov


4 Answers

You can use the built in Math.Max Method

like image 127
crichavin Avatar answered Oct 19 '22 03:10

crichavin


static void Main(string[] args)
{
    Console.Write("First Number = ");
    int first = int.Parse(Console.ReadLine());

    Console.Write("Second Number = ");
    int second = int.Parse(Console.ReadLine());

    Console.WriteLine("Greatest of two: " + GetMax(first, second));
}

public static int GetMax(int first, int second)
{
    if (first > second)
    {
        return first;
    }

    else if (first < second)
    {
        return second;
    }
    else
    {
        throw new Exception("Oh no! Don't do that! Don't do that!!!");
    }
}

but really I would simply do:

public static int GetMax(int first, int second)
{
    return first > second ? first : second;
}
like image 44
FreeNickname Avatar answered Oct 19 '22 05:10

FreeNickname


Since you are returning greater number, as both are same, you can return any number

public static int GetMax(int first, int second)
{
    if (first > second)
    {
        return first;
    }

    else if (first < second)
    {
        return second;
    }
    else
    {
        return second;
    }
}

You can further simplify it to

public static int GetMax(int first, int second)
{
  return first >second ? first : second; // It will take care of all the 3 scenarios
}
like image 4
Tilak Avatar answered Oct 19 '22 05:10

Tilak


If possible to use the List type, we can make use of the built in methods Max() and Min() to identify the largest and smallest numbers within a large set of values.

List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(30);
..

int maxItem = numbers.Max();
int minItem = numbers.Min();
like image 1
Meikanda Nayanar . I Avatar answered Oct 19 '22 05:10

Meikanda Nayanar . I