Diagonal sum

PROBLEM :

Given a square matrix of size M×M . Your task is to calculate the sum of its diagonals.

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. First line of each test case contains a single integer M denoting the size of the square matrix. The next  line contains M*M space separated values of the matrix A.

Output:
For each test case in a new line print the sum of diagonals of the matrix.

Constraints:
1 = T = 20
2 = N = 10
1 = A[i] = 20

Example:

Input:

1
3
1 1 1 1 1 1 1 1 1

Output:
6

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#define MAX 10
int sum_matrix(int [MAX][MAX],int ) ;
int main()
 {
int t,no,mat[MAX][MAX] ;
int i,j ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       for(j=0;j<no;j++)
           cin>>mat[i][j] ;
         
   cout<<sum_matrix(mat,no)<<endl ;
}
return 0;
}

int sum_matrix(int mat[MAX][MAX],int no)
{
    int i,j,sum ;
    sum=0 ;
   
    for(i=0;i<no;i++)
    {
        for(j=0;j<no;j++)
        {
            if(i==j)
                sum=sum+mat[i][j] ;
            if(i+j==no-1)
                sum=sum+mat[i][j] ;
        }
    }
    return sum ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )