Challenge: Row and Column Totals

Lab Java Intermediate 20 points

Read the number of rows r and columns c, then the grid of numbers. Print the total of each row on one line, then the total of each column on the next line (numbers separated by spaces).

Input

First r c, then r lines with c whole numbers each.

Output

Rows: <row totals>
Cols: <column totals>

Example

Input

2 3
1 2 3
4 5 6

Output

Rows: 6 15
Cols: 5 7 9
Sample input available Sample output available
Editor
Java

Hints

Read the grid with two nested loops.

For a row total, keep i fixed and loop over j. For a column total, keep j fixed and loop over i.

Solution explanation

Swapping which loop is on the outside switches between row totals and column totals.

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();
        int c = sc.nextInt();
        int[][] g = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                g[i][j] = sc.nextInt();
            }
        }
        StringBuilder rows = new StringBuilder("Rows:");
        for (int i = 0; i < r; i++) {
            int sum = 0;
            for (int j = 0; j < c; j++) sum += g[i][j];
            rows.append(" ").append(sum);
        }
        StringBuilder cols = new StringBuilder("Cols:");
        for (int j = 0; j < c; j++) {
            int sum = 0;
            for (int i = 0; i < r; i++) sum += g[i][j];
            cols.append(" ").append(sum);
        }
        System.out.println(rows);
        System.out.println(cols);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD