Pratik Thacker Pratik Thacker - 7 months ago 23
Java Question

java multidimensional arrays row sum and column sum

public static void main(String[] args) {
int rows, cols, j, i;
Scanner sc = new Scanner(System.in);
System.out.println("enter no of rows and columns respectively");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows+1][cols+1];
System.out.println("enter elements");
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
matrix[i][j] = sc.nextInt();
}
}
System.out.println("after sum");
int grandtotal = 0;
for(i = 0; i < rows; i++)
{
int rowsum = 0;
int colsum = 0;
for(j = 0; j < cols; j++)
{
rowsum += matrix[i][j];
colsum += matrix[j][i];
}
matrix[i][j] = rowsum;
grandtotal += rowsum;
matrix[j][i] = colsum;
}
j = cols;
matrix[i][j] = grandtotal;


The above code is working fine, but my question is: using this logic, how can I find the
grandtotal
for a matrix if the number of rows and columns are not the same? And tell me if there are any flaws with my current code.

Answer

There is no flaw in your code.Now coming to the point when the number of rows and columns are different.

The statement

matrix[j][i]=colsum;

now would give incorrect result because now number of rows and number of columns are different.

This can be solved very easily by just changing the statement

colsum+=matrix[j][i];

to:

matrix[rows][j]+=matrix[i][j];

and now you do not need the statement

matrix[j][i]=colsum;

So with these simple modifications, the code for different number of columns and rows would be:

for( i=0;i<rows;i++)
{
    int rowsum=0;
    for( j=0;j<cols;j++)
    {
    rowsum+=matrix[i][j];
    matrix[rows][j]+=matrix[i][j];
    }
    matrix[i][j]=rowsum;
    grandtotal+=rowsum;        
}

Keep Rest of the code same.