4.2 Two-dimensional Arrays and Statistics
A two-dimensional array stores values in rows and columns.
cpp
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};The first index chooses the row, and the second index chooses the column.
cpp
std::cout << grid[0][2] << std::endl; // 3
grid[1][0] = 10;Nested loops are the usual way to process a two-dimensional array.
cpp
#include <iostream>
int main() {
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int total = 0;
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
total += grid[row][col];
}
}
std::cout << "Total: " << total << std::endl;
return 0;
}Matrix addition and subtraction work element by element. Values at the same row and column are combined to form the result matrix.
Element-wise Matrix Operations
131012+007521=138533
131012-007521=13-6-5-11
cpp
int A[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int B[3][2] = {{6, 5}, {4, 3}, {2, 1}};
int C[3][2];
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 2; col++) {
C[row][col] = A[row][col] + B[row][col];
}
}For statistics such as row totals, column totals, maximums, or averages, keep one accumulator for the value you are computing and update it inside the correct loop.
Loading interactive lab...
Loading concept check...
Loading practice...