Monday, November 13, 2017

Diagonal Sum - 1

A set of numbers forming a matrix N*N is passed as input. The program has to print the sum of numbers along the diagonals.

Input Format:
The first line will contain the value of N. The next N lines will contain N numbers each separated by one or more spaces.

Boundary Conditions: 2 <= N <= 10 Value of a given number in the matrix is from 0 to 99999999.

Output Format:
The sum of the numbers along the diagonals.

Example Input/Output 1:
Input:
3
5 6 7
8 9 1
2 3 4
Output:
27
Explanation:
The sum of the numbers along the diagonal = 5+9+4+7+2 = 27. Please pay attention in not counting the overlapping number 9 (which is in the middle) twice.

Solution 1:
n=int(input())
a=[[int(i) for i in input().split()]for i in range(n)]
x=sum(a[i][i]+a[i][n-1-i] for i in range(n))
print(x) if n%2==0 else print(x-a[n//2][n//2])

Solution 2:
#include <iostream>
using namespace std;
int main()
{
 int i,j,a,n,s=0;
 cin>>n;
 for(i=0;i<n;i++)
  for(j=0;j<n;j++)
   {
       cin>>a;
       if(i==j||i+j==n-1)
        s+=a;
   }
 cout<<s;
}
Share: