Summing Up A 2D Array

泪湿孤枕 提交于 2019-12-02 08:37:51
Ws Memon

Your code is ok, but at the end for summation of column you should change the rows instead of column. like this:

System.out.println("\n");

    for( int column = 0; column < columns; column++)
    {
        for(int row = 0; row < rows; row++)
            {
            array2d[row][column] = array2d[row][column] + array2d[row][column];
            System.out.print(array2d[row][column] + " ");
            }
         System.out.println();
    }

Welcome to the world of Java. First of let's dissect your "doubling the array" code.

array2d[row][column] = array2d[row][column] + array2d[row][column];

This line of code is the issue. The loops that you have applied tend to update the values of each of the elements in the matrix. For e.g. Suppose

array2d[1][2]=2

Hence the code mentioned above does this

array2d[1][2]= array2d[1][2]+array2d[1][2];

which essentially doubles the value of the array.

You should try something like this:

//To print the values of rows

    for(int i=0;i<rows;i++)
    {
        int rowValue=0;

        for(int j=0;j<columns;j++)
        {

            //Print current row value
            rowValue = rowValue + array2d[i][j];

        }
        System.out.println("ROW" +i+ "=" + rowValue);

    }

The below code will help you calculate the value of columns.

   //To print values of columns
    for(int i=0;i<columns;i++)
    {
        int columnValue=0;

        for(int j=0;j<rows;j++)
        {

            //Print current row value
            columnValue = columnValue + array2d[i][j];

        }
        System.out.println("COLUMN" +i+ "=" + columnValue);

    }

Try making the code for the diagonal.It's pretty straightforward.

HINT : Main diagonals have row and column number to be the same.

P.S. - Add scan.close() to your code. Always close such connections to prevent resource leaks.

For main diagonal

for(int i=0;i<columns;i++)
    {
    for(int j=0;j<rows;j++)
    {
         if(i==j){
          System.out.println(a[i][j]+ "\n"); 
          }
        }

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!