Printing 2D array in matrix format

后端 未结 6 1302
一整个雨季
一整个雨季 2020-12-08 20:12

I have a 2D array as follows:

long[,] arr = new long[4, 4] {{ 0, 0, 0, 0 },
                              { 1, 1, 1, 1 },
                              { 0,          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 20:53

    You can do it like this (with a slightly modified array to show it works for non-square arrays):

            long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };
    
            int rowLength = arr.GetLength(0);
            int colLength = arr.GetLength(1);
    
            for (int i = 0; i < rowLength; i++)
            {
                for (int j = 0; j < colLength; j++)
                {
                    Console.Write(string.Format("{0} ", arr[i, j]));
                }
                Console.Write(Environment.NewLine + Environment.NewLine);
            }
            Console.ReadLine();
    

提交回复
热议问题