Saturday, 10 January 2015

C Program to calculate the trace of a matrix


This is a C Program which calculates the trace of a matrix.

Generally trace of a square matrix is calculated as the sum of all the diagonal elements in a matrix.



PROGRAM :
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int rows,columns,i,j,trace=0;
    printf("Enter order of matrix :  \t");
    scanf("%d%d",&rows,&columns);
    int matrix[rows][columns];
    printf("\nEnter elements of a matrix\n");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            printf("Enter element m%d%d: ",i+1,j+1);
            scanf("%d",&matrix[i][j]);
        }
    }
    printf("\nMATRIX is :\n");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        printf("%d\t",matrix[i][j]);
        
        printf("\n");
    }
    printf("\nIts TRACE is :\t");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            if (i == j)
                trace = trace + matrix[i][j];
            
        }
    }printf("%d\n",trace);
    return 0;
}

OUTPUT :
C - Trace of a matrix