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

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find trace of matrix formed by adding Row-major and Column-major order of same matrix.

For this we will be provided with two arrays one in row-major and other in columnmajor. Our task is to find the trace of the matrix formed by the addition of the two given matrices.

Example

 Live Demo

#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;
}

Output

384
raja
Published on 19-Aug-2020 14:08:03
Advertisements