Multi-Dimensional Arrays (2D Matrices)
int matrix[3][4]; // 3 rows, 4 columns
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
}; // initialized directly
Think of the first index as the row and the second as the column: grid[1][2] refers to row index 1, column index 2 — which holds the value 6 in the example above.
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
printf("%d ", grid[row][col]);
}
printf("\n");
}
Processing a 2D array almost always requires a nested loop — the outer loop walks through rows, the inner loop walks through the columns within each row.
Even though you access a 2D array using two indices, the computer actually stores it as one single, continuous block of memory, row after row (called "row-major order"). Understanding this helps explain why grid[row][col] is really just convenient shorthand the compiler translates into a single calculated memory address behind the scenes.
int matrix[2][2] = {{4, 7}, {2, 5}};
int total = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
total += matrix[i][j];
}
}
printf("Total: %d\n", total); // 18
Writing grid[col][row] instead of grid[row][col] is an easy mistake that either crashes your program (if it goes out of bounds) or, worse, quietly reads the wrong values without any error at all. Always be deliberate about which index represents rows and which represents columns, and stay consistent throughout your program.
Create a 3x3 matrix of your choice, then write nested loops to calculate and print the sum of all its elements.
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int total = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
total += matrix[i][j];
}
}
printf("Sum of all elements: %d\n", total);
return 0;
}