Click here to Skip to main content
15,064,072 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
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

C#
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
Updated 7-Jan-13 18:25pm
v4
Comments
PIEBALDconsult 7-Jan-13 23:48pm
   
So what's the problem? And why are you unsure what your code is?
rameshKumar1717 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.
rameshKumar1717 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.

You want to do two loops, nested.

C#
for(int i =0; i < 3; ++i)
{
for(int j =0; j < 3; ++j)
{
  // add items here
}
}
   
Comments
ridoy 8-Jan-13 1:06am
   
+5
check this

C#
 //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);
 }
   
Comments
ridoy 8-Jan-13 1:06am
   
+5
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:
C#
string[,] arr = new string[,]
    {
        {"A", "F"},
        {"B", "G"},
        {"C", "H"},
        {"D", "I"},
        {"E", "J"}
    };

Refer: 2D Array[^]
   
for(i=0 ; i<now_of_rows; i++ )
{
  for(j=0 ; j<now_of_cols ; j++)
  {
    arr[i][j] = //assign your value here
  }
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900