C Program to calculate the TRACE of a Matrix

In the last two posts, we got familiar with 2-D arrays, by writing programs, to add/subtract and multiply matrices.

In this post we will write a C program to find the Trace of a matrix.

If you haven’t read the last two posts, yet then I will recommend you read them before, reading on.
1. Add/Subtract Matrices using C
2. Multiply matrices using C

Now, the trace is a mathematical object defined for square matrices.
The trace of a square matrices, is the sum of the diagonal terms.
Let A be an n\times n matrix. Then the trace is given as:
Tr(A) = \sum_{i=1}^{n}(a_{ii})

Using, this info, we can write a simple program that reads a matrix and prints the trace.
In this program I will be using two functions.
One for calculating the trace.
The other for reading the matrix.


***********TRACE OF A MATRIX***************
Function that calculates and returns the trace of a square matrix
double trace(int n,double a[n][n]){
	int i;
	double sumDiag=0;
	return sumDiag;
Function that reads the elements of a matrix row-wise
Parameters: rows(m),columns(n),matrix[m][n] 
void readMatrix(int m, int n, double matrix[m][n]){
	int i,j;
	double tr;
	int n,i,j;
	printf("Enter the order of the matrix:\n");
	double a[n][n];
	printf("Enter the elements of the matrix row-wise:\n");
	printf("The trace of the matrix is: %lf",tr);

The program is pretty much self-explanatory. I ask the user to enter the size(order) of the matrix. Then, I declare a matrix(2-d array) of the given size. Then we prompt the user to enter the elements of the matrix, and read them by calling the function in the beginning. Finally, the trace is calculated by calling the trace function.


A sample run of the program is shown below:

YouTube Tutorial:

PhD researcher at Friedrich-Schiller University Jena, Germany. I'm a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT and Machine Learning related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.
[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *