i had programming exam this morning...i failed...
still i wanna know how to do this.
instruction:
create 2d array [5,5] with random number from 0 to 9... and calculate the column...
private void button1_Click(object sender, EventArgs e)
{
int[,] iArray = new int[5, 5];
Random rnumber = new Random();
int inum = rnumber.Next(0, 9);
for (int x = 0; x < iArray.GetLength(0); x++)
{
for (int y = 0; y < iArray.GetLength(1); y++)
{
iArray[x, y] = inum;
label1.Text = inum.ToString();
}
}
}
my code showing only 1 random number. instead of 5 by 5 random number...
Loading
Javeed M ShaikhPosted Nov 9, 2011, 7:14 AM
VulpesPosted Nov 9, 2011, 4:45 AM
When doing something like this it's better to build the string in a temporary variable and then assign the final result to the label's Text property. This avoids the UI having to be updated on each re-assignment.
It would also be more efficient to use a StringBuilder rather than a string when doing a lot of concatenations but no matter :)
Finally, notice that, as your code stood, it was only producing random numbers from 0 to 8 inclusive. When using the Next method you have to remember to make the end-point one more than you need because the random number generated is inclusive of the start-point but exclusive of the end-point.
Jonathan CrispePosted Nov 8, 2011, 11:49 PM
Javeed M ShaikhPosted Nov 8, 2011, 11:08 PM
change...
label1.Text = inum.ToString();
to
label1.Text = label1.Text + " " + inum.ToString();
Jonathan CrispePosted Nov 8, 2011, 11:01 PM
Javeed M ShaikhPosted Nov 8, 2011, 9:45 PM
you code is assigning it correct but the random should be calculated inside the loop, otherwise it will have only one value.
private void button1_Click(object sender, EventArgs e)
{
int[,] iArray = new int[5, 5];
Random rnumber = new Random();
int inum;
for (int x = 0; x < iArray.GetLength(0); x++)
{
for (int y = 0; y < iArray.GetLength(1); y++)
{
inum = rnumber.Next(0, 9);
iArray[x, y] = inum;
label1.Text = inum.ToString();
}
}
}