C++ Two dimension (2D) Array
Two dimension
(2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the index of row and column.
Declaration of 2D Array
data_type array_Name[size_row][size_column];
In the above declaration, data_type is C++ data type, array_Name is the name of array and size_row is the total size of row and size_column is total size of the column of array elements.
Initialization of 2D Array
A 2D array is initialized with data type followed by array name and total row size and column size of elements assignment into array.
int matrix[2][3] = { 6,5,2,3,7,12};
Another best way to initialize the 2D array is as follow:
int matrix[2][3] = { {6,5,2},{3,7,12}};
Access of Array
Elements of an array are accessed through the index
(indices) of that element. The index of array starts from
[00] and end at
[row_size-1column_size-1] of array.
Suppose we want to access the individual elements of a 2D array, this can be done by passing index of the element in array name.
matrix[00]=6;
matrix[01]=5;
matrix[02]=2;
matrix[10]=3;
matrix[11]=7;
matrix[1][2]=12;
Two dimension Array example
Two dimension array are accessed by using two loops (nested loop). The external loop access row of array whereas inner loop access column of the array.
#include <iostream>
using namespace std;
int main()
{
int matrix[2][3] = { {6,5,2},{3,7,12}};
for (int i = 0; i < 2; i++)
{
for(int j=0; j<3; j++ ){
cout<< matrix[i][j]<<endl;
}
}
return 0;
}
Output: