A two-dimensional array can represent a table, matrix, board, or map. It is an “array of arrays”: the first index selects a row and the second selects a column in that row. Both start at 0.
Creating and accessing
int grid[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("%d\n", grid[0][0]); // 1
printf("%d\n", grid[1][2]); // 7Row-column coordinate navigator
Select a value and watch the first index choose a row and the second choose a column.
KNOWLEDGE QUIZ
Rows and columns
Every row of a built-in two-dimensional array has the same column count. This example stores the dimensions in rows and cols; ragged structures require pointers or containers introduced later.
int triangle[3][3] = {
{1, 0, 0},
{1, 2, 0},
{1, 2, 3}
};
int rows = sizeof triangle / sizeof triangle[0];
int cols = sizeof triangle[0] / sizeof triangle[0][0];KNOWLEDGE QUIZ
Nested loops
The outer loop controls rows and the inner loop controls columns. Use cols as the inner bound so the dimension is maintained in one place.
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
printf("%4d", grid[row][col]);
}
printf("\n");
}KNOWLEDGE QUIZ
Matrix addition
Matrix addition and subtraction require matching shapes. The result at position i,j uses only the elements at that same position in the two inputs.
int a[3][2] = {{1, 3}, {1, 0}, {1, 2}};
int b[3][2] = {{0, 0}, {7, 5}, {2, 1}};
int result[3][2] = {0};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 2; col++) {
result[row][col] = a[row][col] + b[row][col];
}
}Matrix addition, one cell at a time
The two input matrices stay on the left while the result starts empty. Each click computes exactly one matching cell.
C[0][0] = 1 + 0 = 1The purple cells mark the values read and written in this step.
KNOWLEDGE QUIZ
Statistics over a 2D array
First decide the scope: one row, one column, or the whole table. This code averages one row; converting to double avoids integer division.
int row = 1;
int sum = 0;
for (int col = 0; col < 4; col++) {
sum += grid[row][col];
}
double average = (double) sum / 4;Add two matrices
Create two 3×2 int arrays, use nested loops to build their sum, and print the result as 3 rows and 2 columns. Do not write each sum manually.
- Store A, B, and result C in two-dimensional arrays.
- Use nested loops over the same row and column coordinates.
- Compute C[row][col] = A[row][col] + B[row][col] and print by rows.
Find the maximum in every row
Use {{4,9,2},{7,1,8},{3,6,5}}. Find the maximum in each row separately and print 9 8 6.
- Use the outer loop to process rows.
- Initialize row_max from the first element of each row.
- Compare remaining columns and print the maximum after each row.