C program to find the trace of matrix

Here, we are going to learn how to find the trace of matrix in C programming language?
Submitted by Nidhi, on July 14, 2021

Problem Solution:

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.

C Two-dimensional Arrays Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.