The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. ― Donald E. Knuth

# C++ Tutorial

## Two Dimensional Arrays

 Module Index ► Introduction to 2D Arrays ( Matrix ) ► Passing 2D Array to Function ► Dynamic memory allocation for Two Dimensional Arrays

Introduction to 2D Arrays ( Matrix )
So, far we have seen one dimensional arrays. Now we will see two dimensional array also known as matrix, which is another useful data structure. Consider the declaration below :

 int mat [ 3 ][ 4 ];

We have declared a two dimensional array or matrix with 3 rows and 4 columns. We can store 3 x 4 = 12 elements in this matrix. Each element is stored in a cell which can be accessed using the combination of
row index and column index. Initialization of a 2D array is shown below :

InitializationIndexing
``````int mat[3][4] = { { 17, 23, 15, 19 },
{ 44, 29, 52, 76 },
{ 21, 63, 35, 57 } };``````

 17 [ 0, 0 ] 23 [ 0, 1 ] 15 [ 0, 2 ] 19 [ 0, 3 ] 44 [ 1, 0 ] 29 [ 1, 1 ] 52 [ 1, 2 ] 76 [ 1, 3 ] 21 [ 2, 0 ] 63 [ 2, 1 ] 35 [ 2, 2 ] 57 [ 2, 3 ]

We can see how the above initialization statement in the left builds a matrix shown in the right. Every element is stored in a cell which has a index shown as subscript of each element. For e.g, 52 is stored in a cell with index
[ 1, 2 ] where 1 denotes the row number ( index ) and 2 denotes the column number ( index ). Please note that both row and column index starts with 0.
Following program inputs a matrix from user and displays it :

Run this program in your system to take input at run-time

Passing 2D Array to Function
2D Arrays (matrices) are passed similar to 1D arrays but the no. of columns must be specified in the argument of the function to which a matrix has been passed. In the following program we implement four functions which takes a matrix as an argument and perform the following functions :
1) Compute sum of left diagonal elements
2) Compute sum of right diagonal elements
3) Print the lower diagonal matrix
4) Print the upper diagonal matrix

Dynamic memory allocation for Two Dimensional Arrays
Similar to 1D arrays, 2D arrays are dynamically allocated and deallocated using new and delete operator.
See the program below :