ในการบวกเมทริกซ์ ให้ใช้เมทริกซ์สองตัว ป้อนแถวและคอลัมน์ของเมทริกซ์หนึ่งและเมทริกซ์ที่สอง โปรดจำไว้ว่า เมทริกซ์ทั้งสองควรเป็นเมทริกซ์สี่เหลี่ยมจัตุรัสเพื่อเพิ่มเข้าไป
ตอนนี้เพิ่มองค์ประกอบให้กับเมทริกซ์ทั้งสอง ประกาศอาร์เรย์ใหม่และเพิ่มทั้งอาร์เรย์ในนั้น
arr3[i, j] = arr1[i, j] + arr2[i, j];
ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Linq;
class Demo {
static void Main() {
int m, n, i, j;
Console.Write("Enter number of rows and columns of the matrix ");
m = Convert.ToInt16(Console.ReadLine());
n = Convert.ToInt16(Console.ReadLine());
int[,] arr1 = new int[10, 10];
int[,] arr2 = new int[10, 10];
int[,] arr3 = new int[10, 10];
Console.Write("Enter elements - Matrix 1 : ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
Console.Write("Enter elements - Matrix 2 : ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr2[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
Console.WriteLine("Matrix 1 ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(arr1[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Matrix 2 ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(arr2[i, j] + "\t");
}
Console.WriteLine();
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr3[i, j] = arr1[i, j] + arr2[i, j];
}
Console.WriteLine();
}
Console.WriteLine("Matrix Addition ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(arr3[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
} ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์
Enter number of rows and columns of the matrix 3 3 Enter elements - Matrix 1 : 1 2 3 4 5 6 7 8 9 Enter elements - Matrix 2 : 1 2 3 4 5 6 7 8 9 Matrix 1 123 456 789 Matrix 2 123 456 789 Matrix Addition 246 81012 141618