C++ - Multi-dimensional Arrays
Multi-dimensional array can be viewed as arrays of arrays. C++ allows you to define multi-dimensional arrays. The following syntax can be used to create a multi-dimensional array.
Syntax
//2-dimensional array of type int //and size (n, m) int MyArray [n][m]; //3-dimensional array of type float //and size (p, q, r) float MyArray [p][q][r]; //n-dimensional array of type double //and size (x1, x2,..., xn) double MyArray [x1][x2]...[xn];
Two-dimensional arrays
The simplest form of the multi-dimensional array is a two-dimensional array. To declare a two-dimensional array of size (3, 4) and type int, the following syntax can be used:
//2-dimension array of type int and size (3, 4) int A [3][4];
This two-dimensional array can be viewed as a table containing three rows and four columns. Additionally, the element of the array can be identified as A[ i ][ j ], where A is the name of the array, and i and j are the row number and column number respectively. The figure below represents this concept:
Initialize two-dimensional arrays
A multi-dimensional array can be initialized by specifying values enclosed by brackets for each row. To initialize a two-dimensional integer array of size (3, 4) the following syntax can be used:
int A[3][4] = { {0, 1, 2, 3}, //initializing row 0 {4, 5, 6, 7}, //initializing row 1 {8, 9, 10, 11} //initializing row 2 };
The nested braces, which indicate the row number are optional. The following initialization is equivalent to previous example:
int A[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Along with this, elements can be initialized individually using the subscripts, i.e, row index and column index of the array as shown below:
A[0][0] = 0; A[0][1] = 1;
Access elements of a two-dimensional array
The elements of the array can be accessed using the subscripts. The example below describes how to initialize and access elements of a 2-dimensional array.
#include <iostream> using namespace std; int main (){ int A[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}}; int B[2][4] = {10, 20, 30, 40, 50, 60, 70, 80}; int C[2][4]; //initializing each element of array C individually int k = 0; for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { C[i][j] = k+10; k++; } } //displaying array A cout<<"Array A contains: \n"; for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { cout<<A[i][j]<<" "; } cout<<"\n"; } //displaying array B cout<<"\nArray B contains: \n"; for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { cout<<B[i][j]<<" "; } cout<<"\n"; } //displaying array C cout<<"\nArray C contains: \n"; for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { cout<<C[i][j]<<" "; } cout<<"\n"; } return 0; }
The output of the above code will be:
Array A contains: 0 1 2 3 4 5 6 7 Array B contains: 10 20 30 40 50 60 70 80 Array C contains: 10 11 12 13 14 15 16 17
❮ C++ - Arrays