How to sum rows and columns of a 2D array individually with Java?

13,709

In your matrix, it is a 3-by-4 matrix from the code segment double[][] matrix = new double[3][4];. The first index is the row index, and the second index is the column index.

Please note that your double[][] matrix is an array of arrays. Namely, matrix is an array of three arrays of length 4, and by convention, each sub-array can be seen as an array of objects arranged in one row. This is called row major order.

For example, in the array

0 1 2 4
0 1 3 9
0 1 5 15

it is really stored as

  • matrix[0]: [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3] and so [0 1 2 4]
  • matrix[1]: [matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3] and so [0 1 3 9]
  • matrix[2]: [matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3] and so [0 1 5 25]

Here is a simpler algorithm that uses loops to find the sum of values for each row and column value, but requires two passes:

/* After the prompt code segment and sumOfCol in the main method */

    // Row (major index)
    for (int row = 0; row < matrix.length; row++) {
        int rowSum = 0;
        for (int col = 0; col < matrix[row].length; col++) {
            rowSum += matrix[row][col];
        }
        System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
    }

    // Column (minor index)
    // Assuming the length of each row is the same
    for (int col = 0; col < matrix[0].length; col++) {
        int colSum = 0;
        for (int row = 0; row < matrix.length; row++) {
            colSum += matrix[row][col];
        }
        System.out.println("Sum of the elements at col " + col + " is: " + colSum);
    }

The output is

Enter a 3 by 4 matrix row by row: 
0 1 2 4
0 1 3 9
0 1 5 15
Sum of the elements at row 0 is: 7
Sum of the elements at row 1 is: 13
Sum of the elements at row 2 is: 21
Sum of the elements at col 0 is: 0
Sum of the elements at col 1 is: 3
Sum of the elements at col 2 is: 10
Sum of the elements at col 3 is: 28
Share:
13,709
Britney
Author by

Britney

Updated on June 05, 2022

Comments

  • Britney
    Britney almost 2 years

    Here is the problem I'm working on: Write a program that reads an 3 by 4 matrix and displays the sum of each column and each row separately.

    Here is the sample run: Enter a 3-by-4 matrix row by row:

    1.5 2 3 4
    5.5 6 7 8
    9.5 1 3 1
    
    Sum of the elements at column 0 is 16.5
    Sum of the elements at column 1 is 9.0
    Sum of the elements at column 2 is 13.0
    Sum of the elements at column 3 is 13.0
    Sum of the elements at Row 0 is: 10.5
    Sum of the elements at Row 0 is: 26.5
    Sum of the elements at Row 0 is: 14.5
    

    and here is the code that I have come up with:

    package multidimensionalarrays;
    
    public class MultidimensionalArrays {
    
        public static void main(String[] args) {
            double sumOfRow = 0;
            double[][] matrix = new double[3][4];
            java.util.Scanner input = new java.util.Scanner(System.in); //Scanner
            System.out.println("Enter a 3 by 4 matrix row by row: ");
            //Prompt user to enter matrix numbers
            for (int row = 0; row < matrix.length; row++) {
                for (int col = 0; col < matrix[0].length; col++) {
                    matrix[row][col] = input.nextDouble();
                }
            }
            double[] sumOfCol =new double[matrix[0].length];  
            for (int i = 0; i < matrix.length; i++) { //row
                for (int j = 0; j < matrix[i].length; j++) { //column
                    sumOfRow += matrix[i][j];
                    sumOfCol[j] += matrix[i][j];
                }
                System.out.println("Sum of the elements at row " + row + " is: " + sumOfRow);
            }
            System.out.println("Sum of the elements at column " + col + " is: " + sumOfCol);
        }             
    }   
    

    My problem is that when it gets to the end to print the sums for columns and rows, it is not recognizing the row or col variables. I've been playing with it and switching things around for probably hours now and I just can't seem to get this right, can someone help me with what I'm doing wrong? Also I don't know if I'm doing the column summing correctly?

    • Ṃųỻịgǻňạcểơửṩ
      Ṃųỻịgǻňạcểơửṩ almost 6 years
      Your current code has a syntax error especially with row and col.
  • Britney
    Britney almost 6 years
    so i replace row with i?
  • Britney
    Britney almost 6 years
    also, do i need to take the column sum completely out of that loop and put into another loop? sorry i am just now learning to code for the first time so this is very confusing to me
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    @Britney There is furthermore a syntax error here. By convention, you view the first coordinate as the row coordinate.
  • Henry
    Henry almost 6 years
    @Britney yes, you used i as row variable. The row sums are computed correctly, just for printing them you need another loop.
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    @Henry I have provided a simpler algorithm. Is there an even more efficient algorithm that only requires one pass to obtain the sums of all the rows and columns?
  • Henry
    Henry almost 6 years
    @Mulliganaceous I did not provide a complete solution on purpose to give the OP a chance to figure it out.
  • Britney
    Britney almost 6 years
    okay you explained this in a way that helped me to better understand this, the arrays have been really confusing me. thank you!!
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    @Britney It is a convention to use the names row and col to index a 2D array in this context
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    @Henry Thanks. However, from the original code, Britney used only one loop and might want to store the results in an auxiliary array such as sumOfCol.
  • Britney
    Britney almost 6 years
    do you mean in place of the i & j that i was using?
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    @Britney yep. You didn't name the index variables consistently. It is good practice to name the consistently
  • Britney
    Britney almost 6 years
    i was thinking that would cause a problem because of me already declaring them in the loop where the user needs to enter the matrix numbers. the same variable name can be declared multiple times in different loops? does this keep them separated?
  • Ṃųỻịgǻňạcểơửṩ
    Ṃųỻịgǻňạcểơửṩ almost 6 years
    The scope of i and j are local. Therefore, names i and j can be repeated in different loops provided that they only exist in the for-loops.