Monday, 10 March 2014

Trace of a square matrix - C++ Program source code

Trace of a square matrix is the sum of elements of the principal diagonal of the matrix.

So without any intro, let's move on to code:
Code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int mat[100][100],tr=0,i,j,m,n;
    cout<<"Enter the order of the matrix : \n";
    cin>>m>>n;
    while(m!=n){
        cout<<"Not a square matrix!\n";
        exit(0);
    }
    cout<<"Enter the elements of the matrix : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cin>>mat[i][j];
        }
    }
    cout<<"The matrix is : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cout<<mat[i][j];
            cout<<"\t";
        }
        cout<<endl;
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            if(i==j){
                tr = tr + mat[i][j];
            }
        }
    }
    cout<<"The trace is "<<tr;
}

Working:
First we input the order of the matrix. If number of columns is not equal to number of rows, the matrix is not a square matrix and will not have a trace. So if they aren't same, the program terminates using exit(0) [in the header <cstdlib>]. Now inside a nested for loop, if an element is on the principal diagonal, then the trace tr, initially set to zero, adds itself to the element. At the end of the loop, tr will be equal to the sum of diagonal elements. 
A couple of sample outputs is given below:




Happy Coding!
:)


No comments:

Post a Comment

You might also like