在 C# 中列印 2D 陣列或矩陣


首先,設定一個二維陣列。

int[,] arr = new int[10, 10];

現在,從使用者那裡獲取元素 −

for (i = 0; i < m; i++) {
   for (j = 0; j < n; j++) {
      arr[i, j] = Convert.ToInt16(Console.ReadLine());
   }
}

讓我們看看顯示矩陣的完整示例。

示例

 即時演示

using System;
using System.Linq;

class Demo {

   static void Main() {

      int m, n, i, j;

      // rows and columns of the matrix+
      m = 2;
      n = 2;

      int[,] arr = new int[10, 10];

      Console.Write("Enter elements of the Matrix: ");
      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {
            arr[i, j] = Convert.ToInt16(Console.ReadLine());
         }
      }

      Console.WriteLine("Printing Matrix: ");
      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {
            Console.Write(arr[i, j] + "\t");
         }
         Console.WriteLine();
      }

      Console.ReadLine();
   }
}

輸出

以下是輸出。

Enter elements of the Matrix: 5 10 12 15
Printing Matrix:
510
1215

最後更新: 27-Mar-2020

2K+ 瀏覽

啟動你的 事業

完成課程認證

開始
廣告
© . All rights reserved.