0

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[][] lala = new int[3][5];
            for(int i=0;i<3;i++)
                for(int j=0;j<4;j++)
                    lala[i][j]= rnd.Next(1, 10);

get an error: 'invalid rank specifier expected ',' or ]'

what is the problem?

thanks

2
  • Invalid syntax. Use int[,] lala = new int[3][5]; or var lala = new int[3][5]; Commented Dec 25, 2013 at 21:08
  • int[][] is a "jagged array", where each major array element can have a different minor array size. Do you want a rectangular array (3x5 array), or a jagged array? Commented Dec 25, 2013 at 21:21

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

He wants to use multidimensional (2d) array... Not jugged.
So he should use the first advice.
You can declare sizes as variables/constants before the loop and then use then to both declare an array and declare loop constraint. Or you can use GetLenght() method: lala.GetLength(0) and lala.GetLength(1) for 2d array. If you decided to use jagged array you can use lala.Length and lala[i].Lenght instead of a method calls. I've updated my answer with complete code which does not use hardcoded values in loop conditions.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.