Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize multi-dimensional array with different default value

I am trying to initialize 2-dimensional array of integer values with -1. When I create a new array, it is automatically filled with 0. I know I can do it with 2 for cycles, but I imagine there should be some way of doing this while the array is being build (so I don't have to go through it two times), so that instead of 0, provided value would be inserted. Is it possible? If not during the initial building of the array, is there some other time or code saving way, or am I stuck with 2 for cycles?

like image 335
kovike Avatar asked Feb 26 '13 00:02

kovike


People also ask

Can you create a 2 dimensional array with different types?

You can have multiple datatypes; String, double, int, and other object types within a single element of the arrray, ie objArray[0] can contain as many different data types as you need. Using a 2-D array has absolutely no affect on the output, but how the data is allocated.

How do you assign values to a multidimensional array?

Assign a value to each element using index Here we declare the array using the size and then assign value to each element using the index. As you can see we assigned the value to each element of the array using the index. That's all for assigning the value to two dimensional array.

How do you declare and initialize a multidimensional array explain by example?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.


1 Answers

Try something like this: int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };

or with dimension int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };

like image 139
TravellingGeek Avatar answered Oct 10 '22 06:10

TravellingGeek