In this tutorial, we will write two different programs to sum the row elements and column elements separately. You may go through the following topic.
Sum of the columns in Java
public class Main
{
public static void main(String[] args)
{
int arr[][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int rows = arr.length;
int cols = arr[0].length;
int sumCols;
for(int i=0; i < cols; i++){
sumCols = 0;
for(int j=0; j < rows; j++)
sumCols += arr[j][i];
System.out.println("sum of "+(i+1)+ " col: "+ sumCols);
}
}
}
Output:
sum of 1 col: 12
sum of 2 col: 15
sum of 3 col: 18
Sum of the rows in Java
public class Main
{
public static void main(String[] args)
{
int arr[][] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int rows = arr.length;
int cols = arr[0].length;
int sumRows;
for (int i = 0; i < rows; i++)
{
sumRows = 0;
for (int j = 0; j < cols; j++)
sumRows += arr[i][j];
System.out.println("sum of " + (i + 1) + "row: " + sumRows);
}
}
}
Output:
sum of 1row: 6
sum of 2row: 15
sum of 3row: 24