Rows, columns, and nested loops
Represent tables and matrices with two-dimensional arrays and traverse them in row-major order.
After this lesson
You should be able to
- Index a two-dimensional array with valid row and column bounds.
- Use nested loops for row, column, and whole-matrix operations.
A table stored row by row
int scores[3][4] represents three rows and four columns. scores[r][c] selects one element. Valid rows are 0–2 and valid columns are 0–3. In ordinary C arrays, each complete row is stored before the next row.
Nested loops mirror the shape: outer loop chooses a row and inner loop visits its columns. Use separate names and bounds; mixing row and column limits may compile but still access invalid memory.
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ", matrix[r][c]);
}
printf("\n");
}Choose the traversal for the question
A row total fixes r and varies c. A column total fixes c and varies r. A diagonal of a square matrix uses matching indexes matrix[i][i]. Naming the intended movement before coding prevents swapped-loop mistakes.
When passing a built-in two-dimensional array to a function, the compiler must know the later dimension so it can calculate row offsets. Variable-length array parameters can carry runtime dimensions in modern C implementations that support them.
Try it yourself
Compute the total of the main diagonal of a 3×3 integer matrix.
Need a hint?
Main-diagonal elements have the same row and column index.
Check the worked solution
Loop i from 0 through 2 and add matrix[i][i].
int total = 0;
for (size_t i = 0; i < 3; i++) {
total += matrix[i][i];
}Quick check
Which traversal computes one column total?
Why this lesson exists
Syllabus mapping
Two-dimensional arrays
Maps to course outcomes CO3, CO5.