Row and Column Sums
Completed
Read r and c, then an r×c matrix. Print each row's sum on one line, then each column's sum on the next.
Input
r c, then r rows.
Output
Two lines.
Example
Input
2 3 1 2 3 4 5 6
Output
6 15 5 7 9
Editor
Java
Hints
m[i][j] is row i, column j.
For column sums, the outer loop goes over columns.
Solution explanation
A 2D array is an array of rows; swapping loop order switches between row-wise and column-wise work.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r = sc.nextInt(), c = sc.nextInt();
int[][] m = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
m[i][j] = sc.nextInt();
}
}
StringBuilder rows = new StringBuilder();
for (int i = 0; i < r; i++) {
int sum = 0;
for (int j = 0; j < c; j++) {
sum += m[i][j];
}
rows.append(sum).append(i < r - 1 ? " " : "");
}
StringBuilder cols = new StringBuilder();
for (int j = 0; j < c; j++) {
int sum = 0;
for (int i = 0; i < r; i++) {
sum += m[i][j];
}
cols.append(sum).append(j < c - 1 ? " " : "");
}
System.out.println(rows);
System.out.println(cols);
}
}