Two / Multi dimensional array in c++


  • In C++ you can define multidimensional arrays with any number of dimensions.
  • The ANSI standard stipulates a minimum of 256 dimensions but the total number of dimensions is in fact limited by the amount of memory available.
  • The most common multidimensional array type is the two-dimensional array, the socalled matrix.
  • Syntax:
     float number[3][10]; // 3 x 10 matrix
    This defines a matrix called number that contains 3 rows and 10 columns. Each of the 30 (3 X 10) elements is a float type.

    Example:
     number[0][9] = 7.2; // Row 0, column 9
  • The two-dimensional array a is said to be a 2×3 array, meaning it has two rows and three columns.
  • Rows are arranged horizontally, and the values in columns are arranged vertically.
  • C++ does not need any special syntax to define multidimensional arrays. On the contrary, an n-dimensional array is no different than an array with only one dimension whose elements are (n–1)-dimensional arrays.

Example

    #include <iostream>
    using namespace std;
    
    int main(){
       int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
       for(int i=0; i<2;i++){
          for(int j=0; j<3; j++){
            cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
          }
       }
       return 0;
    }
    

Output

    arr[0][0]: 11
    arr[0][1]: 22
    arr[0][2]: 33
    arr[1][0]: 44
    arr[1][1]: 55
    arr[1][2]: 66