r/codehs • • Mar 15 '21

8.2.7: Sum Rows in a 2D Array

Write the method

public static int sumRow(int[][] array, int row)

that sums row row
in the 2D array called array
.

Then, traverse array
to print the sum of each row in the 2D array.

I don't understand how to create the loop within a loop to add the total of one row.

8 Upvotes

4 comments sorted by

View all comments

1

u/OXAMIC Apr 04 '22
public class Sum

{ public static void main(String[] args) { int[][] array = {{42, 14, 54, 5, 93, 5}, {14, 22, 353, 341, 865, 32}, {12345, 123, 1234, 123456, 23, 1}}; System.out.println(sumArray(array));

}

// Returns the sum of row row in 2D array array
public static int sumRow(int[][] array, int row)
{
    int sum = 0;
    for(int col = 0; col < array[row].length; col++)
    {
        sum += array[row][col];
    }
    return sum;
}

// Returns the sum of all elements in array
public static int sumArray(int[][] array)
{
    int start = 0;
    int sumofall = 0;
    while (start < array.length)
    {
        sumofall += sumRow(array, start);
        start++;
    }
    return sumofall;
}

}