Oops! It appears that you have disabled your Javascript. In order for you to see this page as it is meant to appear, we ask that you please re-enable your Javascript!

Program to Find Sum of Diagonals of Matrix in CPP (C plus plus)

Program to Find Sum of Diagonals of Matrix in CPP (C plus plus)

In this tutorial, we will learn about Program to Find Sum of Diagonals of Matrix in CPP (C plus plus).

#include<iostream>
 
using namespace std;
 
int main()
{
    int array[5][5];
	int d1sum=0;
	int d2sum=0;
	int k;
	int i;
	int j;
    
    cout<<"Please enter size of the square matrix (MAX 5):";
    cin>>k;
    
    cout<<endl<<"Please enter the Matrix row wise:"<<endl;
    
    for(i=0;i<k;i++)
        for(j=0;j<k;++j)
            cin>>array[i][j];
            
    for(i=0;i<k;++i)
        for(j=0;j<k;++j)
        {
            if(i==j)
                d1sum+=array[i][j];
            if(i+j==(k-1))
                d2sum+=array[i][j];
        }
    
    cout<<endl<<"The sum of First diagonal is: "<<d1sum;
    cout<<endl<<"The sum of Second diagonal is: "<<d2sum;
 
    return 0;
}

Output:

Program to Find Sum of Diagonals of Matrix in CPP (C plus plus)

Program to Find Sum of Diagonals of Matrix in CPP (C plus plus)