basics · beginner · ~15 min

Diagonal sum

Walk the diagonal (i, i) of a flattened square matrix.

Challenge

Sum the main diagonal of a square matrix stored as a flat array.

Task

Implement long diag_sum(const int *m, int n) that returns the sum of the main-diagonal elements of an n x n row-major matrix m. The diagonal entries are (0,0), (1,1), ..., (n-1,n-1), which sit at flat offsets i*n + i. Accumulate into a long. No main — the grader calls it.

Input

A flat array m holding an n x n matrix, and the dimension int n (n >= 1).

Output

Returns the sum of the main diagonal, as a long.

Example

m = {1,2,3, 4,5,6, 7,8,9}   (3 x 3)
diag_sum(m, 3)   ->   15     (1 + 5 + 9)

m = {5}                       (1 x 1)
diag_sum(m, 1)   ->   5

Edge cases

  • A 1x1 matrix returns its single element.

Input format

A flat array m of an n x n matrix, and the dimension int n (n >= 1).

Output format

The sum of the main diagonal, as a long.

Constraints

Row-major; diagonal element i is at offset i*n + i.

Starter code

long diag_sum(const int *m, int n) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.