Find trace and normal of matrix in C++

This C++ program is able to find the trace and normal of a matrix in the same way that we find in mathematics.

Basically the trace of a matrix is the sum of main diagonal of a matrix and normal is square root of sum of all the elements.

Similar to all other operations applicable on a matrix, this program is also possible to perform in a much simple and time efficient manner by the use of programming. Instead of manually doing these jobs, writing some lines of code which will work for us is better. I am going to show you how.

Trace and normal of a matrix in C++


  • Define a matrix(integer array) and assign values for the matrix.
  • Define separate variables to store normal, trace and dimensions of array.
  • To find normal the sum of all the elements and then the square root of the result and store it in a variable.
  • To find trace find the sum of main diagonal elements where row and column dimensions are equal for matrix the store the result in a variable.
  • Print the result on screen.


Following is the program code to find trace and normal of a matrix. It is written and successfully compiled in CodeBlocks v 16.01 in windows 10.

#include <iostream>

using namespace std;

int main()
    int matrix[3][3]={{2,3,5},{7,4,5},{8,5,4}};     //declaration and values assignment of array
    int trace=0;
    float normal;

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            normal=normal+matrix[i][j];     //sum of all elements

            if(i==j)                        // condition for trace of matrix

    normal=sqrt(normal);                //sqrt() id defined in math.h header file

    cout<<"Following is the matrix"<<endl;

    for(int i=0;i<3;i++){               // print matrix elements
        for(int j=0;j<3;j++)

    cout<<"Normal of matrix: "<<normal<<endl;
    cout<<"Trace of matrix: "<<trace<<endl;


Following is the matrix
2 3 5
7 4 5
8 5 4
Normal of matrix: 6.55744
Trace of matrix: 10

ProgramĀ explanation

  1. Declare a matrix of size 3X3 assigned values to it.
  2. Declare variables, normal as float and trace as int.
  3. Run a nested for loop to sum all the elements values in normal variable.
  4. Along with this use if condition as row==column then sum diagonal elements in trace variable.
  5. Perform the square root of the normal variable by using predefined function sqrt().
  6. Print the matrix elements followed by trace and normal variables on the screen.

Also, read

Find the next greater number from the same set of digits in C++


Leave a Reply

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