I want to create 2d array in C#. size: 3 on 5, and insert into random numbers. I try that but it\'s not work:
Random rnd = new Random();
int[][]
Change your array declaration
int[,] lala = new int[3,5];
and assignment operation
lala[i,j]= rnd.Next(1, 10);
to use 2d array syntax of jagged array.
or if you want to use jagged array, you have to declare only the most outer size in first declaration and then declare the inner size within the loop:
Random rnd = new Random();
int[][] lala = new int[3][];
for(int i=0;i<3;i++)
{
lala[i] = new int[5];
for(int j=0;j<4;j++)
lala[i][j]= rnd.Next(1, 10);
}
Update
Complete codes for jagged array:
Random rnd = new Random();
int[][] lala = new int[3][];
for (int i = 0; i < lala.Length; i++)
{
lala[i] = new int[5];
for (int j = 0; j < lala[i].Length; j++)
lala[i][j] = rnd.Next(1, 10);
}
and 2d array
Random rnd = new Random();
int[,] lala = new int[3,5];
for (int i = 0; i < lala.GetLength(0); i++)
{
for (int j = 0; j < lala.GetLength(1); j++)
lala[i,j] = rnd.Next(1, 10);
}
Here it is:
Random rnd = new Random();
int[,] lala = new int[3,5];
for(int i=0;i<3;i++)
{
for(int j=0;j<5;j++)
{
lala[i, j]= rnd.Next(1, 10);
Console.WriteLine("[{0}, {1}] = {2}", i, j, lala[i,j]);
}
}
working sample: http://dotnetfiddle.net/4Fx9dL