4.2 2D Arrays and Sequence Statistics
A two-dimensional array can represent a table, matrix, or board. It has row and column indexes.
c
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("%d\n", grid[1][2]); // 6grid[1][2] means: take row 1, then take column 2 inside that row. Both indexes start from 0.
Matrix addition can be done with nested loops. The outer loop controls rows, and the inner loop controls columns.
Matrix addition and subtraction require two matrices with the same shape. If and are both matrices, then the result matrix is also . "Element by element" means row , column is only combined with row , column from the other matrix.
Element-wise Matrix Operations
131012+007521=138533
131012-007521=13-6-5-11
c
int A[3][2] = {
{1, 3},
{1, 0},
{1, 2}
};
int B[3][2] = {
{0, 0},
{7, 5},
{2, 1}
};
int C[3][2];
printf("Matrix Addition\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
printf("%3d", C[i][j]);
}
printf("\n");
}Result:
text
Matrix Addition
1 3
8 5
3 3Common array statistics include sum, average, maximum, and minimum.
c
int scores[] = {88, 91, 76, 95, 83};
int n = sizeof(scores) / sizeof(scores[0]);
int max = scores[0];
for (int i = 1; i < n; i++) {
if (scores[i] > max) {
max = scores[i];
}
}sizeof(scores) / sizeof(scores[0]) only works while scores is still an array in the current scope.
Loading interactive lab...
Loading concept check...
Loading practice...