basics · beginner · ~15 min
Walk the diagonal (i, i) of a flattened square matrix.
Sum the main diagonal of a square matrix stored as a flat array.
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.
A flat array m holding an n x n matrix, and the dimension int n (n >= 1).
Returns the sum of the main diagonal, as a long.
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
A flat array m of an n x n matrix, and the dimension int n (n >= 1).
The sum of the main diagonal, as a long.
Row-major; diagonal element i is at offset i*n + i.
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.