C Program to Find the Trace of a Matrix

Write a C program to find the trace of a matrix using for loop. The trace of a matrix is the sum of its diagonal. In this C example, if(i == j) finds the matrix diagonal elements and adds them to trace.

#include <stdio.h>

int main()
{
	int i, j, rows, columns, trace = 0;

	printf("Enter Matrix Rows and Columns =  ");
	scanf("%d %d", &rows, &columns);

	int Tra_arr[rows][columns];

	printf("Please Enter the Matrix Items =  \n");
	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < columns; j++)
		{
			scanf("%d", &Tra_arr[i][j]);
		}
	}

	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < columns; j++)
		{
			if (i == j)
			{
				trace = trace + Tra_arr[i][j];
			}
		}
	}

	printf("The Trace Of the Matrix = %d\n", trace);
}
C Program to Find the Trace of a Matrix

C program to find the trace of a matrix using a while loop.

#include <stdio.h>

int main()
{
		
		int i, j, rows, columns, trace = 0;	
		
		printf("Enter Matrix Rows and Columns =  ");
		scanf("%d %d", &rows, &columns);
		
		int Tra_arr[rows][columns];
		
		printf("Please Enter the Matrix Items =  \n");
		i = 0; 
		while(i < rows) 
		{
			j = 0; 
			while(j < columns) 
			{
				scanf("%d", &Tra_arr[i][j]);
				j++;
			}	
			i++;
		}
		
		i = 0; 
		while(i < rows) 
		{
			j = 0; 
			while(j < columns) 
			{
				if(i == j)
				{
					trace = trace + Tra_arr[i][j];
				}
				j++;
			}	
			i++;
		}
		
		printf("The Trace Of the Matrix = %d\n", trace);

}
Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =  
10 30 50
70 90 120
150 170 290
The Trace Of the Matrix = 390

This C example calculates and prints the trace of a given matrix using the do while loop.

#include <stdio.h>

int main()
{

	int i, j, rows, columns, trace = 0;

	printf("Enter Matrix Rows and Columns =  ");
	scanf("%d %d", &rows, &columns);

	int Tra_arr[rows][columns];

	printf("Please Enter the Matrix Items =  \n");
	i = 0;
	do
	{
		j = 0;
		do
		{
			scanf("%d", &Tra_arr[i][j]);
			if (i == j)
			{
				trace = trace + Tra_arr[i][j];
			}
		} while (++j < columns);
	} while (++i < rows);

	printf("The Trace Of the Matrix = %d\n", trace);
}
Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =  
10 20 30
40 50 60
70 80 90
The Trace Of the Matrix = 150

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.