C++ Multi-dimensional Array
In the previous topic we have learnt about the basic concepts of array in C++. In this tutorial we are looking for another type of an array called multi-dimensional array.
Table of content
C++ Multi-dimensional Array :
In C++ we can create multidimensional array.Syntax to create multidimensional array is as below -
data-type name[size1][size2]...[sizeN];
Suppose we need to create the 2-dimensional array then we can declare it as -
int mat[5][4];
The above 2-dimensional array consists of the 5 rows and 4 columns.
Two-Dimensional Arrays:
- Simplest form of the multidimensional array is the two-dimensional array.
- 2-dimensional array is also called as matrix or table.
- 2-dimensional array has 2 dimensions.
- First dimension represents the number of row
- Second dimension represents the number of columns.
Example of 2-dimensional array :
Consider the 2-dimensional array of size x,y then we can declare it like
data_type nameOfArray [ x ][ y ];
where -
- data_type will be any valid C++ data type
- nameOfArray will be name of 2-dimensional array.
- x will be number of rows
- y will be number of columns
Representation :
| Cell Location | Meaning |
|---|---|
| a[0][0] | 0th Row and 0th Column |
| a[0][1] | 0th Row and 1st Column |
| a[0][2] | 0th Row and 2nd Column |
| a[0][3] | 0th Row and 3rd Column |
| a[1][0] | 1st Row and 0th Column |
| a[1][1] | 1st Row and 1st Column |
| a[1][2] | 1st Row and 2nd Column |
| a[1][3] | 1st Row and 3rd Column |
| a[2][0] | 2nd Row and 0th Column |
| a[2][1] | 2nd Row and 1st Column |
| a[2][2] | 2nd Row and 2nd Column |
| a[2][3] | 2nd Row and 3rd Column |
Two-Dimensional Array : Summary with Sample Example
| Summary Point | Explanation |
|---|---|
| No of Subscript Variables Required | 2 |
| Declaration | a[3][4] |
| No of Rows | 3 |
| No of Columns | 4 |
| No of Cells | 12 |
| No of for loops required to iterate | 2 |
Initializing the 2-D array :
int a[3][2] = { { 1 , 4 }, /*Initialize 0th row*/ { 5 , 2 }, /*Initialize 1st row*/ { 6 , 5 } /*Initialize 2nd row*/ };
We can alternatively declare it as -
int a[3][2] = {1,4,5,2,6,5};
