ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อค้นหาการติดตามของเมทริกซ์ที่เกิดขึ้นจากการเพิ่มลำดับแถวหลักและคอลัมน์หลักของเมทริกซ์เดียวกัน
สำหรับสิ่งนี้เราจะมีอาร์เรย์สองอาร์เรย์หนึ่งรายการในแถวหลักและอีกรายการในคอลัมน์หลัก งานของเราคือการหาร่องรอยของเมทริกซ์ที่เกิดขึ้นจากการบวกเมทริกซ์ทั้งสองที่กำหนด
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
//calculating the calculateMatrixTrace of the new matrix
int calculateMatrixTrace(int row, int column) {
int A[row][column], B[row][column], C[row][column];
int count = 1;
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++) {
A[i][j] = count;
count++;
}
count = 1;
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++) {
B[j][i] = count;
count++;
}
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
C[i][j] = A[i][j] + B[i][j];
int sum = 0;
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
if (i == j)
sum += C[i][j];
return sum;
}
int main() {
int ROW = 6, COLUMN = 9;
cout << calculateMatrixTrace(ROW, COLUMN) << endl;
return 0;
} ผลลัพธ์
384