Q:

C program to find the trace of matrix

0

C program to find the trace of matrix

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Trace of a n x n square matrix is sum of diagonal elements. Given a square matrix, we have to find the trace of matrix.

Program:

The source code to find the trace of Matrix is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the trace of Matrix

#include <stdio.h>

int main()
{
    int Matrix[3][3] = {
        { 9, 8, 7 },
        { 5, 4, 6 },
        { 1, 2, 3 }
    };

    int i, j, trace = 0;

    printf("Matrix:\n");
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j) {
            printf(" %d", Matrix[i][j]);
        }
        printf("\n");
    }

    //Find trace of elements
    for (i = 0; i < 3; ++i)
        trace = trace + Matrix[i][i];

    printf("Trace of matrix is: %d\n", trace);

    return 0;
}

Output:

Matrix:
 9 8 7
 5 4 6
 1 2 3
Trace of matrix is: 16

Explanation:

Here, we created a 3X3 matrix matrix using the 2D array. Then we find the trace of the matrix. After that, we printed the Matrix and trace of matrix on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to print the upper triangular matrix... >>
<< C program to find the normal of a matrix...