WAP to find the trace of a matrix.

Write a program to find the trace of a matrix.

#include<stdio.h>

int main() {
	int a[5][5],sum=0,row,column,i,j;

	printf("Enter matrix size.\n");
	scanf("%d%d",&row,&column);

	if(row==column){
		printf("Enter elements in array:\n");
		for(i=0;i<row;i++){
			for(j=0;j<column;j++){
				printf("a[%d][%d]=",i,j);
				scanf("%d",&a[i][j]);
			}
			sum+=a[i][i];
		}
		printf("Trace = %d",sum);
	}
	else
		printf("Not a square matrix so trace can not be defined.");

	return 0;
}

Output

Enter array size.
2
2
Enter elements in array:
a[0][0]=1
a[0][1]=2
a[1][0]=3
a[1][1]=4
Trace = 5

Behind the scene

a[0][0] + a[1][1] = 1 + 4 = 5

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments