Monday, 30 June 2014

Maximum Sum

Write a program that reads an NxN square matrix M that calculates the sum of the elements in individual rows, individual columns and the two main diagonals. Among these sums, print the largest.
Consider the following matrix of order 3x3:
1 10 13
2 14 12
3  9   8
The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is maximum among these sums, which is 33.

INPUT:
First line contains a value N representing the dimension of the input matrix M, followed by N lines, each line representing a row of the matrix. Within each row, N values are given and are separated by whitespace.

OUTPUT:
A value which is the maximum among N row sums, N column sums and the two main diagonal sums in M.

CONSTRAINTS:
The entries in M are integers.
1<=N<=100
-100 <= Mij <= 100

Solution:

#include<stdio.h>
int main()
{
int a[100][100];//input matrix
int n;//dimension of the square matrix
int i,j;//loop variables
int sum=-10001;//variable that holds the maximum among a set of rows/columns/diagonals that are considered so far
int temp_sum;//variable that holds partial sum of values in a row/column/diagonal
scanf("%d",&n); //read dimension
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);//read input values
for(i=0;i<n;i++)
{ temp_sum=0;//reset the variable before storing the partial sum of values in a row under consideration
for(j=0;j<n;j++)
{
temp_sum=temp_sum+a[i][j]; //calculate the sum of elements in the i^th row
}
if(temp_sum>sum)//check whether the sum of values in the i^th row is better than the current maximum
{
sum=temp_sum;
}
}
for(i=0;i<n;i++)
{ temp_sum=0;//reset the variable before storing the partial sum of values in a column under consideration
for(j=0;j<n;j++)
{
temp_sum=temp_sum+a[j][i];//calculate the sum of elements in the i^th column
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the i^th column is better than the current maximum
}
}
temp_sum=0;//reset the variable before storing the partial sum of values in the first diagonal
for(i=0;i<n;i++)
{
temp_sum+=a[i][i];//calculate the sum of elements in the first diagonal
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the first diagonal is better than the current maximum
}
temp_sum=0;//reset the variable before storing the partial sum of values in the second diagonal
for(i=0;i<n;i++)
{
temp_sum+=a[i][n-1-i];//calculate the sum of elements in the second diagonal
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the second diagonal is better than the current maximum
}
printf("%d",sum);
return 0;
}

No comments: