C program to find the trace of a given square matrix
We know that the trace of a matrix is defined as the sum of the leading diagonal elements.
Note : Trace is possible only for a square matrix.
# include<stdio.h>
main( )
{
int a[10][10], m,i,j, sum;
printf ("\n Enter order of the square matrix :") ;
scanf ("%d", &m);
printf ("\n Enter the matrix \n");
for( i=0; i<m;i++)
for ( j=0; j<m; j++)
scanf ("%d", &a[i ][ j ]);
/* loop to find trace of the matrix */
sum = 0;
for ( i=0; i<m; i++)
sum = sum + a[i ][ i ];
printf ("\n trace of the matrix = %d", sum);
}
Output:

Trace of A matrix = A11+A22+A33=3+1+2=6
Row i and column j are equal for a diagonal element.
When this program is executed, the user has to enter the order m & values of the given matrix. A for loop is written to find the sum of the diagonal elements. The index variable of the loop i is used for row & column subscripts to represent the diagonal elements.
Share: