Lesson 4 of 12

Matrices: think in two coordinates

Traverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.

Rows and columns have separate bounds

int a[2][3] contains two rows of three cells each. a[1][2] is valid; a[2][1] is not. The first index selects the row, and the second selects a column in that row.

For active dimensions rows and columns, require 0 ≤ r < rows and 0 ≤ c < columns. a[0][3] is not a legal shortcut for a[1][0]. A complete traversal visits rows × columns cells, even if the physical capacity is larger.

Fix one coordinate, vary the other

For a row sum, keep the row fixed and visit all columns. For a column sum, keep the column fixed and visit all rows. Start a new long long sum for each new row or column.

To print a transpose, visit original columns in the outer loop and original rows in the inner loop. A 2 × 3 table becomes 3 × 2. Access remains a[r][c]; only the visiting order changes. Storing a transpose separately uses b[c][r] = a[r][c].

C++23
#include <iostream>

int main() {
    int a[30][30]{};
    int rows = 0, columns = 0;
    std::cin >> rows >> columns; // Each dimension is 1..30.
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < columns; ++c) { std::cin >> a[r][c]; }
    }
    for (int c = 0; c < columns; ++c) {
        for (int r = 0; r < rows; ++r) {
            if (r > 0) { std::cout << ' '; }
            std::cout << a[r][c];
        }
        std::cout << '\n';
    }
    return 0;
}

Two diagonals can share a centre

In a square n × n matrix, main-diagonal cells satisfy r == c. The other diagonal satisfies r + c == n − 1. Equivalently, its column in row r is n − 1 − r.

For odd n the diagonals share a centre cell. If printing two separate sums, the centre belongs in both. If summing distinct diagonal cells, count it once. One condition joined by || naturally includes each visited cell at most once.

Guard the four grid neighbours

A grid of characters can use an array of strings, one string per row. After converting a chosen one-based position to zero-based, inspect up, down, left, and right individually. Diagonals are excluded unless the task explicitly includes them.

Bounds must come first: r > 0 && grid[r − 1][c] == '.' prevents an invalid upward access at row 0. Test a 1 × 1 grid, a single row, a single column, and a nonsquare grid to expose swapped bounds.

Pause & predict

In a 5 × 5 matrix, which cell belongs to both diagonals?

Choose an answer
Try it yourself

Turn the idea into code

For 1 ≤ n ≤ 30 and matrix values in [−10⁹, 10⁹], sum all distinct cells on either diagonal. For the 3 × 3 matrix containing 1 through 9 by rows, print 25.

Give me a hint

Use one if condition: r == c OR r + c == n − 1.

Show the explained solution

The shared centre enters one addition, because a single true condition performs one update. A long long safely holds the sum under these bounds.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    int a[30][30]{};
    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < n; ++c) { std::cin >> a[r][c]; }
    }
    long long sum = 0;
    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < n; ++c) {
            if (r == c || r + c == n - 1) { sum += a[r][c]; }
        }
    }
    std::cout << sum << '\n';
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.