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?
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.
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.
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.
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} };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With