2D array
A two-dimensional array is an array that has two indexes for each element ( often such arrays are called with one word - matrix).
It is convenient to store and process various tabular data in a matrix. Just like any table is made up of rows and columns, matrices are made up of rows and columns.
For clarity, you can represent an array like this:
Although, in fact, in the computer's memory, the matrix will look like this:
To use a matrix in a program, it must be declared just like a regular array, specifying the data type and two sizes (numbers or constants). It is also possible (and desirable) to immediately set the initial values. For example, reset all elements.
Example 1: Declaring an array of 3 rows and 3 columns with arbitrary initial values
intA[3][3] = {{0,1,2},
{3,4,5},
{6,7,8} };
Example 2: Declaring an array of 5 rows and 10 columns (the size is set via a constant) with zero initial values
const int N = 5, M = 10;
double B[N][M] = {};
To refer to a specific element of the matrix, we use two pairs of brackets, in the first bracket we indicate the row number, in the second - the column number.
Example:
A[0][2] = 100; //numbering of rows and columns starts from zero
Filling the matrix and displaying it
In order to traverse the entire matrix, a nested loop is needed. Let's look at filling and outputting a matrix using the example of a program that requests the values of elements from the keyboard and simply displays the filled matrix on the screen.
#include <iostream>
using namespace std;
int main() {
/* Declaring a two-dimensional array */
const int N = 2, M = 3;
int A[N][M];
/* fill in the elements of the matrix from the keyboard line by line */
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
cin>> A[i][j];
//Display all elements of the matrix on the screen line by line
for (i = 0; i < N; i++) { //outer loop is responsible for iterating over rows
for (j = 0; j < M; j++) //loop to display the elements of the string
cout << A[i][j] << " ";
cout << endl; //after displaying the elements of the j-th line, we move to a new line
}
return 0;
}
In the above example, both filling and displaying the matrix occurs row by row (first we go through all the values
j - the index of the columns, and only then the row index changes -
i)
By swapping loops (inner with outer), you can fill and / or output an array by columns