How can I initialize Multidimensional Array [][] in c# with int [3][3]?


Hi, How can I initialize Multidimensional Array [][] in c# with int [3][3] (3 rows and 3 columns )? Like below

4 8 2 
4 5 7
6 1 6

I want to put it in this array int [][] magicsquare;

my current code is as below but it is not throwing error,

int[][] magicsquare = new int { { 4, 8, 2 }, { 4, 5, 7 }, { 6, 1, 6 } }; 

can you help me, please.

Thanks


Asked by:- LuneAgile
1
: 2020 At:- 7/18/2018 12:11:05 PM
C# 3D-array-initialization







1 Answers
profileImage Answered by:- vikas_jk

You can create three dimenstional array as shown in below C# code

 // Create a three-dimensional array.
        int[, ,] threeDimensional = new int[3, 5, 4];

Here is the complete sample which may help

https://qawithexperts.com/tutorial/c-sharp/26/c-sharp-multidimensional-array

https://qawithexperts.com/tutorial/c-sharp/27/c-sharp-jagged-array

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

Above links will clear your concepts related to multi-dimensional array. The one which you were trying to create :

int[][] magicsquare;

Is array of arrays, which is 2-D only, but your requirement is for 3-D array.

To consider differece between 2d array and jagged array

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays)

2
At:- 7/18/2018 12:26:45 PM Updated at:- 9/27/2022 7:39:08 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use