2D Matrix Row-Wise & Column-Wise Sum Program in Java

⚡ Direct Answer & Key Takeaway

To compute row-wise and column-wise totals of an `M x N` integer matrix in Java, use two separate nested `for` loops. Keep the outer loop variable `i` fixed on rows while `j` sweeps across columns to accumulate `rowSum` and reset it to zero before each new row. Swap the loop order—keeping column index `j` in the outer loop and `i` inside—to accumulate `colSum` vertically for every column in ICSE BlueJ programs.

1. How Index Swapping Controls Traversal Direction

A two-dimensional array `arr[r][c]` stores elements in row-major memory where the first subscript selects the horizontal row and the second chooses the vertical column. When calculating row totals, the outer `for` loop holds row index `i` steady from `0` to `r - 1` while inner index `j` steps from `0` to `c - 1`. Initializing `rowSum = 0` inside the outer loop guarantees each row begins fresh. Conversely, summing vertically requires `j` outside and `i` inside so `arr[i][j]` walks down one fixed column before advancing to the next.

  • Use `arr.length` for total rows and `arr[0].length` for total columns in rectangular arrays.
  • Always reset `rowSum = 0` inside the outer loop, never outside the nested structure.
  • Index `arr[i][j]` with outer `j` and inner `i` reads elements top-to-bottom per column.
  • Works identically for square (`3 x 3`) and rectangular (`3 x 4`) matrices without modification.

2. Dry Run on a 3x4 Rectangular Matrix

Consider a `3 x 4` array holding `{ {4, 7, 2, 5}, {9, 1, 6, 3}, {8, 5, 0, 4} }`. During horizontal traversal at `i = 0`, `rowSum` adds `4 + 7 + 2 + 5` to yield `18`, prints it, and resets. At `i = 1`, `rowSum` becomes `19`, and at `i = 2` it reaches `17`. Switching to vertical mode for `j = 0`, inner variable `i` visits `arr[0][0]`, `arr[1][0]`, and `arr[2][0]`, adding `4 + 9 + 8` to print `21`. Repeating for `j = 1, 2, 3` produces column sums `13`, `8`, and `12`.

  • Row 0 total: `4 + 7 + 2 + 5 = 18`; Row 1 total: `19`; Row 2 total: `17`.
  • Column 0 total: `4 + 9 + 8 = 21`; Column 1: `13`; Column 2: `8`; Column 3: `12`.
  • Cross-check grand total: sum of rows (`54`) must equal sum of columns (`54`).

3. ICSE Section A & Section B Scoring Rules

CISCE examiners award full 15 marks in Section B when your BlueJ program separates input, processing, and formatted output cleanly while avoiding `ArrayIndexOutOfBoundsException`. In Section A two-mark questions, students frequently get snippets asking to predict output when loop limits mix up `r` and `c` on non-square matrices. Using `r` exclusively as the upper bound for row index `i` and `c` strictly for column index `j` keeps rectangular arrays safe. Adding a concise Variable Description Table right after the code secures the mandatory documentation marks.

  • Keep separate `int r, c` variables rather than assuming `r == c`.
  • Print row numbers as `i + 1` and column numbers as `j + 1` for human-friendly output.
  • Verify every variable in your code appears in the Variable Description Table.

4. MatrixRowColSum.java (ICSE BlueJ)

import java.util.*;

public class MatrixRowColSum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of rows and columns: ");
        int r = sc.nextInt();
        int c = sc.nextInt();

        int[][] arr = new int[r][c];
        System.out.println("Enter " + (r * c) + " matrix elements:");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        System.out.println("\nMatrix:");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }

        System.out.println("\nRow-wise Sums:");
        for (int i = 0; i < r; i++) {
            int rowSum = 0;
            for (int j = 0; j < c; j++) {
                rowSum += arr[i][j];
            }
            System.out.println("Row " + (i + 1) + " sum = " + rowSum);
        }

        System.out.println("\nColumn-wise Sums:");
        for (int j = 0; j < c; j++) {
            int colSum = 0;
            for (int i = 0; i < r; i++) {
                colSum += arr[i][j];
            }
            System.out.println("Column " + (j + 1) + " sum = " + colSum);
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter number of rows and columns: 3 4
Enter 12 matrix elements:
4 7 2 5 9 1 6 3 8 5 0 4

Matrix:
4	7	2	5	
9	1	6	3	
8	5	0	4	

Row-wise Sums:
Row 1 sum = 18
Row 2 sum = 19
Row 3 sum = 17

Column-wise Sums:
Column 1 sum = 21
Column 2 sum = 13
Column 3 sum = 8
Column 4 sum = 12

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
scScannerReads matrix dimensions and integer elements from keyboard
r, cintStore row count and column count (sample: r = 3, c = 4)
arr[][]int[][]2D array holding 3x4 input matrix elements
i, jintLoop counters for row index (0..2) and column index (0..3)
rowSumintAccumulates sum of one row per iteration (e.g., 18, 19, 17)
colSumintAccumulates sum of one column per iteration (e.g., 21, 13, 8, 12)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master 2D Array Traversals in Live 1-on-1 BlueJ Sessions

Practice rectangular matrix dry runs, loop-bound debugging, and VDT formatting with an ICSE Computer Applications mentor before your pre-boards.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Declaring `rowSum = 0` before the outer `for` loop instead of inside it, causing cumulative sums across rows instead of per-row totals.
  • Avoid Mistake: Using `i < r` for the inner loop when computing column sums, which triggers `ArrayIndexOutOfBoundsException` whenever `r != c`.
  • Avoid Mistake: Writing `arr[j][i]` while keeping `j < c` and `i < r`, which accidentally swaps indices and crashes on rectangular grids.
  • Examiner / Mentor Tip: Display the original matrix in grid format using `\t` before printing sums so the examiner can visually verify every total.
  • Examiner / Mentor Tip: When asked for a single-pass solution in viva, explain that maintaining a `int[] colTotals = new int[c]` array allows computing both row and column sums in one nested loop.
  • Examiner / Mentor Tip: Always verify your dry run by checking that the sum of all `rowSum` values equals the sum of all `colSum` values.

7. Interactive Concept Check Quiz

Question: Given a rectangular integer matrix `int[][] m = new int[3][5];`, which outer and inner loop bounds correctly calculate every column's sum using `m[i][j]`?

8. Frequently Asked Questions

Can we compute row sums and column sums inside the same nested loop in Java?
Yes, you can calculate `rowSum` per row and simultaneously add `arr[i][j]` into a 1D array `colSum[j]` inside a single nested loop. However, CISCE board marking schemes prefer two separate loops when memory optimization is not requested because separate loops keep logic cleaner and avoid allocating extra auxiliary arrays.
What happens if the user enters non-square dimensions like 2 rows and 5 columns?
The program works seamlessly for any positive dimensions `r` and `c` because row bounds use `r` and column bounds use `c` independently. Only diagonal and symmetry programs strictly require a square matrix where `r == c`, whereas row-wise and column-wise totals apply cleanly to every rectangular 2D array.
Why do we print (i + 1) instead of i in the output statement?
Java arrays use zero-based indexing, so the first row is stored at index `0` and the first column at index `0`. Displaying `Row 1` and `Column 1` via `(i + 1)` and `(j + 1)` matches standard mathematical matrix notation expected by ICSE board examiners.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class