Find trace of matrix formed by adding Row-major and Column-major order of same matrix in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds trace of matrix formed by row and column major matrices.

Let's see how to form a row and column major matrices when order of the matrix is given.

Order − 3 x 3

Row Major Matrix

123
456
789

Column Major Matrix

147
258
369

We have row and column major matrices. Now, we have to add both the matrices. And the trace of the resultant matrix is the result that we are looking for.

Let's see write the code to solve the problem. We have to complete the following 4 steps to finish the solution for the problem.

  • Create the row-major matrix.

  • Create the column-major matrix.

  • Add the both matrices and store the resultant matrix.

  • Find the trace of the resultant matrix and print the result.

Example

Let's see the code.

 Live Demo

#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int traceOfRowAndColumnMajorMatrices(int m, int n) {
   int row_major[m][n], column_major[m][n], addition_result[m][n], count = 1;
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         row_major[i][j] = count;
         count += 1;
      }
   }
   count = 1;
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         column_major[j][i] = count;
         count += 1;
      }
   }
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         addition_result[j][i] = row_major[i][j] + column_major[i][j];
      }
   }
   int trace = 0;
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         if (i == j) {
            trace += addition_result[i][j];
         }
      }
   }
   return trace;
}
int main() {
   int m = 3, n = 3;
   cout << traceOfRowAndColumnMajorMatrices(m, n) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

30

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 10:33:52
Advertisements