Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding maximum & minimum number from 2 numbers in an array

Tags:

c#

I'm trying to find the maximum and minimum numbers out of 2 integers that a user has inputted. Firstly i have converted the string to int, then went to put them into an array so i can manipulate them. I think i'm getting stuck when it comes to assigning variables to an array. But i couldn't see any examples of arrays with variables assigned to them, which is probably where i'm going wrong.

    private void button1_Click(object sender, EventArgs e)
    {
       string txtbxnum1 = Int32.Parse(num1);
       string txtbxnum2 = Int32.Parse(num2);

       int[] numbers = new int[2] {0,1};
       int numbers [0] = num1;
       int numbers [1] = num2;

       int maximumNumber = Max.numbers();
       int minimumNumber = Min.numbers();
       MessageBox.Show (maximumNumber.Text);
    }

I would be glad of any help or direction.

like image 210
user1735367 Avatar asked Oct 24 '12 21:10

user1735367


1 Answers

If all you have is two numbers, you do not need an array: System.Math provides functions to find the smaller and the larger of two numbers, called Math.Max and Math.Min.

// Int32.Parse takes a string, and returns an int, not a string:
int n1 = Int32.Parse(num1);
int n2 = Int32.Parse(num2);
// Math.Min and Math.Max functions pick the min and max
int min = Math.Min(n1, n2);
int max = Math.Max(n1, n2);
// Show both numbers in a message box in one go using String.Format:
MessageBox.Show(string.Format("Min:{0} Max:{1}", min, max));
like image 72
Sergey Kalinichenko Avatar answered Nov 14 '22 23:11

Sergey Kalinichenko