4

I'm currently messing around with 2D arrays. I want to Fill a 2D array with a count. I've managed to do this using 2 nested for loops. (That's probably the easiest way of doing it right?)

//create count
int count = 1;

for (int row = 0; row < matrix.GetLength(0); row++)
{
    for (int col = 0; col < matrix.GetLength(0); col++)
    {
        matrix[row, col] = count++;
    }
}

I was just curious, is it also possible to fill this 2D array using only a single for loop?

I thought of making a loop that counts the rows. When the rows reaches the end of the array the column wil be increased by 1. This could probably be done by using some if, if else and else statements right?

Does someone here have any idea how to make this work?

3
  • 1
    That code doesn't work for arrays where the row and column sizes are different, as it references matrix.GetLength(0) for both. You should change the second call to matrix.GetLength(1). Commented Nov 26, 2018 at 12:06
  • 1
    Yes. You would need to use module arithmetic. Suppose a array is 8 x 8 and you used a index (i) of 0 to 63. The row number would be i/ 8. The column would be i % 8. Commented Nov 26, 2018 at 12:09
  • Just for fun int GetArrayValue(int row, int col, int colLength) { return (col * colLength) + row } Commented Nov 26, 2018 at 12:18

2 Answers 2

6

Here you go

int[,] matrix = new int[5, 10];     
int row = matrix.GetLength(0);
int col = matrix.GetLength(1);      

for (int i = 0; i < row * col; i++)
{
    matrix[i / col , i % col] = i + 1;
}

https://dotnetfiddle.net/Lv9DvT

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, of course you can.

for(int i = 0; i < matrix.GetLength(0) * matrix.GetLength(1); i++)
{
    int row = i / matrix.GetLength(1);
    int column = i % matrix.GetLength(1);

    matrix[row, column] = i;
}

Works with NxN arrays.

4 Comments

@fubo Why? You will iterate over all elements (4x4 have 16 elements) and we have the column and row by a simple math
Actually I forgot two things: work with NxN arrays and fill the array.
This populates the column then increments the row, OP wanted it the other way around so just swap row and column
I already edited my comment with addent of works only with NxN (quad arrays)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.