You are on page 1of 3

PRACTICAL – 05

AIM:
To write a programme to compute trace of a matrix

QUESTION:
Write a programme in C to compute trace of a matrix.

THEORY:
The trace of a matrix is given by the sum of its diagonal elements.

( )
a 11 ⋯ a 1 n
A= ⋮ ⋱ ⋮
an 1 ⋯ ann

tr ( A )=a11 + a22 +a33±−∓ann

Trace of a matrix is only defined if the given matrix is a square matrix.

C – CODE:
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int a[5][5],tr=0,r1,c1,i,j;
clrscr();
printf("Enter the size of the matrix \n");
scanf("%d%d",&r1,&c1);
printf("Enter the matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
if(i==j)
tr = tr + a[i][j];
}
}
printf("Trace of the matrix is %d",tr);
getch();
}

****************************************************************************************

OUTPUT
****************************************************************************************
Enter the size of the matrix
3
3
Enter the matrix
234
345
456
Matrix A
2 3 4
3 4 5
4 5 6
Trace of the matrix is 12

RESULT:
The trace of a matrix can be found using the above code. Here, trace of the matrix is 12.

You might also like