C++ Program to Find Trace of a Matrix

Trace of Matrix

C++ program to find trace of a given matrix has been shown here. Suppose A is a matrix, then trace of matrix A is denoted as tr(A) which is sum of elements on main diagonal. Only a square matrix can have a trace.


Examples:


$A = \begin{bmatrix} 1 & 5 & 6\\ 0 & 4 & 3\\ 2 & 7 & 8 \end{bmatrix}$

So, the trace of matrix A = 1 + 4 + 8 = 13






1. Algorithm to Find Trace of a Matrix


1. Take a matrix $A_{m\times n}$ as input

2. Check if $m=n$

3. If step [2] is false then display "Input matrix is not a square matrix!" and exit program

4. If step [2] is true, then

5. Set $sum = 0$

6. For each $i = j$, successively add $A_{ij}$ to $sum$, where $i \in [1, m]$ and $j \in [1, n]$

7. Declare $sum$ as the trace of the matrix and exit program.




2. Pseudocode to Find Trace of a Matrix


Input: A matrix $A_{m\times n}$

Output: Trace of matrix $A_{m\times n}$

1. Procedure traceOfMatrix($A_{m\times n}$):

2. If $m == n$:

3. $sum \leftarrow 0$

4. Repeat for each $i = j$ where $i \in [1, m]$ and $j \in [1, n]$

5. $sum \leftarrow sum + A_{i,j}$

6. Return $sum$

7. Else:

8. Return It should be a square matrix

9. End Procedure





3. Time Complexity to Find Trace of a Matrix


Time Complexity: O($m$)

Where $m$ is the number of rows and columns in the given square matrix.




4. C++ Program to Find Trace of a Matrix

Code has been copied
/*************************************
        alphabetacoder.com
C++ Program to find trace of a matrix 
**************************************/
#include <iostream>

using namespace std;

int main() {
    // declare variables
    int m, n, i, j, sum;
    int A[10][10] = {0};

    //take input of the order of the matrix
    cout << "Enter the number of rows and columns of matrix = ";
    cin >> m >> n;

    //take input of the matrix
    cout << "Enter the elements of matrix of order " << m << " x " << n << " = " << endl;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            cin >> A[i][j];

    // check if the matrix is a square matrix or not
    // if it is square matrix, find the trace
    if (m != n)
        cout << "\nInput matrix is not a square matrix!" << endl;
    else {
        // initialize
        sum = 0;
        // find trace of matrix
        for (i = 0; i < m; i++) {
            sum += A[i][i];
        }
        cout << "\nTrace of given matrix: " << sum;
    }

    return 0;
}

Output


Enter the number of rows and columns of matrix = 3 3

Enter the elements of matrix of order 3 x 3 =

5 6 4

0 2 1

1 2 0


Trace of given matrix: 7