Johnny Johnny - 12 days ago 5
C# Question

How to add a column to the an array C#

i am able to create a dynamic array entered by the use, but i need to have a starting fixed array that is not entered by the user:

Here is an example:

Entered and printed array is:


1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5


I need to add a column of 0s at the beginning of the array like so:


0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5


Thank you!

Answer

Say you enter 3 rows and 2 columns for r and c. Then input the values. The output is:

1 2

1 2

1 2

But now I want that to appear as:

0 1 2

0 1 2

0 1 2

The number of rows (vertical) is the same. But the number of columns (horizontal) has increased from 2 to 3 since I've added the extra column for 0's.

So in code we have to account for the extra column:

    int r;
    int c;
    Console.Write("Enter number of rows: ");
    r = (int)Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter number of columns: ");
    c = (int)Convert.ToInt32(Console.ReadLine());
    c++; //add an extra column for the added 0's
    int[,] matrix = new int[r, c];

Now we want to add the 0's to this column. But we need to be able to specify that we only want to add 0's for the first column. When we're filling the arrays we can add a check to say that if the column we are currently filling is the very first column for a row then automatically insert a 0.

    for (int row = 0; row < r; row++)
    {
        for (int col = 0; col < c; col++)
        {
            if (col == 0)
            {
                matrix[row, col] = 0;
            }
            else
            {
                Console.Write("Enter value for matrix[{0},{1}] = ", row, col);
                matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
            }
        }
    }

The first entry that the user is asked to enter is no longer {0,0} since the very first entry would've been automatically entered, but do you really care? If so you can just minus 1 from the display value there:

    Console.Write("Enter value for matrix[{0},{1}] = ", row, col -1);
Comments