Reputation: 19
Please help, I'm supposed to use two separate methods (one for columns, one for rows) in order to sum up each separate row and column of 2d arrays and print them out (ex: row 1 = , row 2 = , col 1 = , col 2 = ). So far I have two separate methods that get me only the first row and column separately, but I'm stuck on how to print out the other rows/cols without changing the return value. Here's what I have so far:
public class FinalSumRowColumn
{
public static void main(String[] args)
{
int[][] mat = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
System.out.println("\nSum Row 1 = " + sumRow(mat));
System.out.println("\nSum Col 1 = " + sumCol(mat));
}
public static int sumRow(int[][] mat)
{
int total = 0;
for (int column = 0; column < mat[0].length; column++)
{
total += mat[0][column];
}
return total;
}
public static int sumCol(int[][] mat)
{
int total = 0;
for (int row = 0; row < mat[0].length; row++)
{
total += mat[row][0];
}
return total;
}
}
Upvotes: 2
Views: 203
Reputation: 2823
Add one more parameter to each method: int index
, for example:
public static int sumRow(int[][] mat, int index)
{
int total = 0;
for (int column = 0; column < mat[index].length; column++)
{
total += mat[index][column];
}
return total;
}
And when you print:
for (int i = 0; i < mat.length; i++) {
System.out.println("Sum Row " + (i+1) + " = " + sumRow(mat, i));
}
Upvotes: 0
Reputation: 124704
Add a row
and col
parameter for these methods, for example:
public class FinalSumRowColumn {
public static void main(String[] args) {
int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("\nSum Row 1 = " + sumRow(mat, 0));
System.out.println("\nSum Col 1 = " + sumCol(mat, 0));
System.out.println("\nSum Row 1 = " + sumRow(mat, 1));
System.out.println("\nSum Col 1 = " + sumCol(mat, 1));
System.out.println("\nSum Row 1 = " + sumRow(mat, 2));
System.out.println("\nSum Col 1 = " + sumCol(mat, 2));
}
public static int sumRow(int[][] mat, int row) {
int total = 0;
for (int column = 0; column < mat[row].length; column++) {
total += mat[row][column];
}
return total;
}
public static int sumCol(int[][] mat, int col) {
int total = 0;
for (int row = 0; row < mat[0].length; row++) {
total += mat[row][col];
}
return total;
}
}
Upvotes: 1
Reputation: 53535
Change your method definition from:
public static int sumRow(int[][] mat)
to:
public static int sumRow(int[][] mat, int row)
and then later on sum the row that was passed to the method:
total += mat[row][column];
Same goes for sumCol()
.
Upvotes: 1
Reputation: 738
Why don't you add a parameter to both your methods to indicate the index of the row or column you want to sum?
For example public static int sumRow(int[][] mat, int row)
Upvotes: 1