Easy–medium · 2D arrays

Sum a Matrix

Read a rows x cols matrix and print the sum of all entries. First nested-loop problem where the shape of the input matters.

At a glanceRead rows and cols, then add every entry in a double loop — the inner loop must read cols numbers per row, not rows.

Problem

Input: First line: rows and cols. Then rows lines of cols integers.

Output: The sum of every entry.

Sample:

InputOutput
2 3
1 2 3
4 5 6
21

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — You do not need a 2D array

To just sum, read each value into a temporary and add it. A 2D array is only needed if you revisit entries later.

Hint 2 — Nested loops, row-major

for (i < rows) for (j < cols) { cin >> v; sum += v; } — input arrives row by row.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cin >> rows >> cols;
    int sum = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            int v;
            cin >> v;
            sum += v;
        }
    }
    cout << sum << endl;
    return 0;
}

Stretch goals: sum only the main diagonal, or transpose the matrix — both need the 2D array you skipped here.

Deep dive

Why this works

Nested loops matching the shape of the data — rows × cols — is the mental model for all two-dimensional work. C++ stores row-major, so loop order has a real cache cost.

The cost

O(r·c) time, O(1) extra space if you sum while reading.

Where it goes wrong

  • Swapping the bounds (columns outer, rows inner) is still correct but walks memory in the wrong order — several times slower on large matrices.
  • int m[100][100] on the stack is 40 KB. Bigger sizes overflow the stack instead of failing gracefully.

Next step

One-dimensional patterns you now combine: Array Maximum.

Two things to remember

  • Loop order should match memory order (row-major).
  • Sum while reading — you never need the matrix.
🐞 This version fails — open it and try

i < rows - 1 skips the last row

#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cin >> rows >> cols;
    int sum = 0;
    for (int i = 0; i < rows - 1; i++) {
        for (int j = 0; j < cols; j++) {
            int v;
            cin >> v;
            sum += v;
        }
    }
    cout << sum << endl;
    return 0;
}