TheBoringGuy
TheBoringGuy

Reputation: 151

Method 2d-array display

Hi my question is how do I display all the numbers in my 2 dimensional array. I only manage to display the total sum of all the number of my array. If you could help me I be very thankful.

    int[,] A = new int[5, 7];
    Random rand = new Random();
    private void SumAll(int[,] array)
    {
        int sum = 0;
        int rows = array.GetLength(0);
        int cols = array.GetLength(1);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                    array[i, j] = rand.Next(-100, 100);
                    sum += array[i, j];
                    richTextBox1.AppendText(array[i, j] + "Sum is: " + sum);
            }
        }
        richTextBox1.Text = (sum.ToString());
    }

Upvotes: 0

Views: 95

Answers (2)

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

I guess, you are overwriting all changes with this line:

richTextBox1.Text = (sum.ToString());

Change it to:

richTextBox1.AppendText(sum.ToString());

UPD: to display grid-like use this:

   for (int i = 0; i < rows; i++)
   {
      for (int j = 0; j < cols; j++)
         {
            array[i, j] = rand.Next(-100, 100);
            sum += array[i, j];
            richTextBox1.AppendText(array[i, j] + " ");
         }
         richTextBox1.AppendText("Sum is: " + sum);
         richTextBox1.AppendText(System.Environment.NewLine);
   }
   richTextBox1.AppendText("Total sum: " + sum);

Upvotes: 1

pennstatephil
pennstatephil

Reputation: 1643

You should use the same nested for loop structure that you used to generate the numbers and create the sum, just printing each element along the way.

Upvotes: 0

Related Questions