C# declaring a 2D array

前端 未结 5 1059
梦如初夏
梦如初夏 2021-01-19 17:13

I am trying to setup a 2d array in C# to act as a maze to move a character around, I am having a few issues initialising the array, I am trying to do the below

but t

5条回答
  •  走了就别回头了
    2021-01-19 17:42

    Two-Dimensional Arrays

    The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays.

    A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns −

    Two Dimensional Arrays in C#

    Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.

    Initializing Two-Dimensional Arrays

    int [,] a = new int [3,4] {
    
       {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
    
       {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
    
       {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
    
    };
    

    Explain above code:

    new int [**3**,4] **3** denoting to rows like how may object in array 
    
    eg:
    
    {0, 1, 2, 3} ,  
    {4, 5, 6, 7} ,  
    {8, 9, 10, 11}
    
    
    new int [3,**4**] **4** denoting to columns like total value in object (4 columns)
    
    eg:   
    
    
       {0, 1, 2, 3}
    

    Let us check the program to handle a two dimensional array

     using System;
        namespace ArrayApplication {
           class MyArray {
              static void Main(string[] args) {
                 /* an array with 5 rows and 2 columns*/
                 int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
                 int i, j;
    
                 /* output each array element's value */
                 for (i = 0; i < 5; i++) {
    
                    for (j = 0; j < 2; j++) {
                       Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
                    }
                 }
                 Console.ReadKey();
              }
           }
        }
    
    Output:  
    
    a[0,0]: 0
    a[0,1]: 0
    a[1,0]: 1
    a[1,1]: 2
    a[2,0]: 2
    a[2,1]: 4
    a[3,0]: 3
    a[3,1]: 6
    a[4,0]: 4
    a[4,1]: 8
    

提交回复
热议问题