12,951,971 members (64,344 online)
Rate this:
See more:
Hi, I want to fill 2d array using for loop, I want to enter 9 rows in 2d array with 3 record in each row my code is something like this, I want test array should contain
9 rows with 3 elements in each row. In case of this code no new row has been added to the array rather first row is updated each time

```for (int i = 0; i < 9; ++i)
{
test[i] = 1;
// arr[i] = [9]{1,2,3};
//test[i]={1,2,3};
for (j = 0; j < 2; ++j)
{
int[][] test = new int[] { 1, 2, 3 };
}
}```
Posted 7-Jan-13 17:36pm
Updated 7-Jan-13 18:25pm
v4
PIEBALDconsult 7-Jan-13 23:48pm

So what's the problem? And why are you unsure what your code is?
ramesh0285 7-Jan-13 23:54pm

i am not getting this can u suggest me code its not adding new row, only updating first row with new value instead of adding second one.
ramesh0285 8-Jan-13 0:32am

in above simple code, in my original code element of 2d array will be value of pixels in an image so finally my 2d array would contain 1024 rows with 9 element in each row. plz help me this is college assignment.

Rate this:

## Solution 1

You want to do two loops, nested.

```for(int i =0; i < 3; ++i)
{
for(int j =0; j < 3; ++j)
{
}
}```
ridoy 8-Jan-13 1:06am

+5
Rate this:

## Solution 3

check this

```
//declare new 2d array
int[,] test=new int[9,3];

for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 3; ++j)
{

//setting value for each element
test[i, j] = 1;
}
}

//writing the elements in console window

foreach (int i in test)
{
// MessageBox.Show(i.ToString());
Console.WriteLine(i);
}```
ridoy 8-Jan-13 1:06am

+5
Rate this:

## Solution 2

Other then using two for-loops, if you have a small 2-D array, you can do it at the time of defining array itself.
Example:
```string[,] arr = new string[,]
{
{"A", "F"},
{"B", "G"},
{"C", "H"},
{"D", "I"},
{"E", "J"}
};```

Refer: 2D Array[^]
Rate this:

## Solution 4

```for(i=0 ; i<now_of_rows; i++ )
{
for(j=0 ; j<now_of_cols ; j++)
{
arr[i][j] = //assign your value here
}
}
```
v2

Top Experts
Last 24hrsThis month
 OriginalGriff 490 CPallini 135 Maciej Los 130 CHill60 110 F-ES Sitecore 105
 OriginalGriff 6,239 CHill60 3,490 Maciej Los 3,083 Jochen Arndt 1,975 ppolymorphe 1,880