Tim
Tim

Reputation: 55

copying array from button1 to button2

i'm beginner at c# and programming in total.. so i'm working on this code in school right now, where i have to generate 21 random numbers between 1-21 (you can have duplicates of numbers). i have made the code and it's working sorta... it generates the numbers in listbox1 but it's not the same numbers i get sorted in listbox3.

private void button1_Click(object sender, EventArgs e)
        {
            int[] a = new int[21];
            Random tal = new Random();


            for (int x = 1; x < a.Length; x++)
            {
                a[x] = tal.Next(1, 21);
            }
            for (int x = 1; x < a.Length; x++)
            {
                listBox1.Items.Add(a[x]);
            }
            foreach (int i in a)
            {
                Array.Sort(a);
                listBox3.Items.Add(a[i]);
            }
            int min = a[1];
            for (int x = 1; x < a.Length; x++)
                if (a[x] < min)
                    min = a[x];
            listBox2.Items.Add(min);
            int max = a[20];
            for (int x = 1; x > a.Length; x++)
                if (a[x] < max)
                    max = a[x];
            listBox2.Items.Add(max);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int[] a = new int[21];
            Random tal = new Random();
            a.Clone();

            foreach (int i in a)
            {
                Array.Sort(a);
                listBox3.Items.Add(a[i]);
            }
        }
    }
}

Upvotes: 0

Views: 51

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61369

Variables have scope.

What this means for you right now, is that the a in button1_Click is not the same as the a in button3_Click (not to mention they are assigned to different arrays).

If you need them to be shared, a should be declared at the class level (ie, not in a method). Then both methods can use the same variable (just don't re-assign it!).

Also:

  • a.Clone(); doesn't do anything unless you assign the result
  • Calling Sort in your loop is totally overkill
  • Random tal = new Random() isn't even used in button3_click

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

1.Array begin with index 0, so change all your loops to start from 0:

 for (int x = 0; x < a.Length; x++)

instead of

for (int x = 1; x < a.Length; x++)

and also int min = a[0]; not int min = a[1];

2.Sort the array outside the for loop, there is no need to do it over and over:

Array.Sort(a);
foreach (int i in a)
{
    listBox3.Items.Add(a[i]);
}

the items must be the same (but different order).

and also you are cloning a (a.Clone();) and actually not assigning it to anything, so its an extra code.

Upvotes: 1

Related Questions