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 ShaikhRank #839 · 2.7K reputationPosted Nov 8, 2011, 4:45 PM EST
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();
}
}
}
Jonathan Crispe46 reputationPosted Nov 8, 2011, 6:01 PM EST
Javeed M ShaikhRank #839 · 2.7K reputationPosted Nov 8, 2011, 6:08 PM EST
change...
label1.Text = inum.ToString();
to
label1.Text = label1.Text + " " + inum.ToString();
Jonathan Crispe46 reputationPosted Nov 8, 2011, 6:49 PM EST
VulpesRank #55 · 29.2K reputationPosted Nov 8, 2011, 11:45 PM EST
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.
Javeed M ShaikhRank #839 · 2.7K reputationPosted Nov 9, 2011, 2:14 AM EST