เมทริกซ์คืออาร์เรย์สองมิติ ตัวอย่าง 4×3:
3 5 1 7 1 9 3 9 4 1 6 7
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int r=2, c=4, sum[2][4], i, j;
int a[2][4] = {{1,5,9,4}, {3,2,8,3}};
int b[2][4] = {{6,3,8,2}, {1,5,2,9}};
cout << "The first matrix is: " << endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout << a[i][j] << " ";
cout << endl;
}
cout << endl;
cout << "The second matrix is: " << endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout << b[i][j] << " ";
cout << endl;
}
cout << endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
sum[i][j] = a[i][j] + b[i][j];
cout << "Sum of the two matrices is:" << endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout << sum[i][j] << " ";
cout << endl;
}
return 0;
}
ผลลัพธ์
The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12
อธิบายขั้นตอน
1. กำหนดเมทริกซ์ a และ b ขนาด 2×4 แสดงทั้งคู่
2. บวกเมทริกซ์: sum[i][j] = a[i][j] + b[i][j] (ต้องขนาดเท่ากัน):
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
sum[i][j] = a[i][j] + b[i][j];
3. แสดงผลรวม