 # C Program to find the trace and normal of a matrix

August 10, 2021, Learn eTutorial
710

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this c program, we need to calculate the trace and normal of a matrix. A matrix is a collection of elements of the same data type, which we arrange in a 2d format. A matrix is also called an array of arrays.

## How to calculate the trace of a matrix?

Trace is the Sum of all elements of the Main diagonal of a Matrix. For example, The Trace of Matrix A :

2 5
2
1 is 3.

## How to calculate the normal of a matrix?

The normal of a matrix is the square root of the Sum of squares of the elements of Matrix. For example, The Normal of Matrix B:

2 10
8  5
is 5. That is the Square root of 25.

So here in this c program, what we are doing is to initialize the variables and import the header files. Then accept a matrix using a nested `for loop` and calculate the square of each element. Now add the product to a sum variable. Find out the normal by calculating the square root of the sum.

For finding a trace of that matrix, we initiate a `for loop` where we add the elements of the main diagonal of the matrix. Then we display the normal and the trace of the matrix using the `printf` function.

### ALGORITHM

STEP 1: Include the Header files to use the built-in functions in the C program.

STEP 2: Include the Header file math.h.

STEP 3: Declare the variable i, j, m, n, sum, sum1, a, normal and set sum=0, sum1=0, a=0.

STEP 4: Read the order of the Matrix into the variables m and n.

STEP 5: Read the coefficients of the matrix into the array ma[i][j] and calculate a=ma[i][j]*ma[i][j] ,sum1=sum1+a using nested `for loop`.

STEP 6: Calculate Normal=sqrt(sum1).

STEP 7: Display the normal of the given Matrix is normal.

STEP 8: By using the `for loop` with the condition i

STEP 9: Display the Trace of the Matrix as a sum.

## C Source Code

```                                          ```#include <stdio.h>
#include <math.h>

void main() {
static int ma;
int i, j, m, n, sum = 0, sum1 = 0, a = 0, normal;
printf("Enter the order of the matrix\n");
scanf("%d %d", & m, & n);
printf("Enter the no coefficients of the matrix \n");
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
scanf("%d", & ma[i][j]);
a = ma[i][j] * ma[i][j];
sum1 = sum1 + a;
}
}
normal = sqrt(sum1);
printf("The normal of the given matrix is = %d\n", normal);
for (i = 0; i < m; ++i) {
sum = sum + ma[i][i];
}
printf("Trace of the matrix is = %d\n", sum);
} /*End of main() */```
```

## OUTPUT

```Enter the order of the matrix
3*3

Enter the n coefficients of the matrix
1 2 3
4 5 6
7 8 9

The normal of the given matrix is = 16
Trace of the matrix is = 15

Run 2

Enter the order of the matrix
2*2

Enter the n coefficients of the matrix
2 4
6 8

The normal of the given matrix is = 10

Trace of the matrix                       = 10
```