javaarraysmultidimensional-array

How to get the sum of the elements in the last column of each row in a two-dimensional array?


I'm working on this program where I'm suppose to find the sum of the elements in the last column of each row in a two-dimensional array of integers.

So far I have this code which works just fine:

public class Lab {

public static void main(String[] args) {

    int[][] arr = { { 2, 4, 5, 7 }, { 4, 8, 7, 5 }, { 5, 9, 2, 20 } };
    
    //getting each array from multidimensional array (arr)
    int[] firstRow = arr[0];
    int[] secondRow = arr[1];
    int[] lastRow = arr[arr.length - 1];
    
    //getting last element in each row
    int lastItemInFirstRow = firstRow[firstRow.length - 1]; // 7
    int lastItemInSecondRow = secondRow[secondRow.length - 1];// 5
    int lastItemInLastRow = lastRow[lastRow.length - 1];  // 20
    
    
    //sum of the elements in the last column of each row in a two-dimensional array
    // 7 + 5 + 20
    System.out.println(lastItemInFirstRow + lastItemInSecondRow + lastItemInLastRow); //32
 }
}

However, I need to create a method more efficient than that. For example what if I have 20 arrays inside my multidimensional array. If I try the code above it will take many lines of code. So I have created a method which takes care of the sum of the elements in the last column of each row, but I'm not sure how to get the actual sum. Someone help me please. Thanks a lot!

Here's my method:

public static int sumOfElementsInLastColumn(int[][] arr){
    
    int sum = 0;
    
    for(int row = 0 ; row < arr.length; row++){
        for(int column = 0 ; column < arr[row].length ; column++){
            sum += arr[row][arr.length];
        }
    }
    return sum;
    
}

Solution

  • public static int sumOfElementsInLastColumn(int[][] arr)
    {
        int sum = 0;
    
        for (int i = 0; i < arr.length; i++)
        {
            int [] row = arr[i];
    
            sum += row[row.length - 1];
        }
        return sum;
    }