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 <stdio.h>

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

    //take input of the order of the matrix
    printf("Enter the number of rows and columns of matrix = ");
    scanf("%d%d", & m, & n);

    //take input of the matrix
    printf("Enter the elements of matrix of order %d x %d = \n", m, n);
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", & A[i][j]);

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

    return 0;
}

Output


Case 1:

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

1 2 3 4

5 6 7 8

9 0 1 2

3 4 5 6


Trace of given matrix: 14



Case 2:

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

Enter the elements of matrix of order 2 x 3 =

1 2 3

4 5 6


Input matrix is not a square matrix!