multi-dimensional array in C++

multi Dimensional array in C++ are a collection of the single-dimensional array in C++. value is stored as a table from in it.

here is syntax below-

syntax

Storage-class data-type array-name[size1][size2][size3].....;

To avoid complexity, here we will only discuss two -dimensional arrays which can be a good choice for understanding multi dimensional arrays in C ++.

data-type array-name[size1][size2];

in two-dimensional array size1 represents row and size2 column.

int arr[2][3];

row × column, then

2×3=6 it will store 6 elements, such as in table form below-

initialization of two-dimensional array in C++

multi-dimensional array initialization is similar to normal array. i.e-

data_type array_name[size1][size2]={list};

Example

int arr[2][3]={3,2,4,1,6,7};

or

int arr[2][3]={ 
                 {3,4.6}, 
                 {2,1,7} 
              };

as we know, the first size as row while second as the column, such as,

multi-dimensional-array-cpp

means,

x[0][0] = 3
x[0][1] = 4
x[0][2] = 6
x[1][0] = 2
x[1][1] = 1
x[1][2] = 7

In the below program, we take the elements from the user and accessing them,

accessing of a two-dimensional array element

Like the single-dimensional array, the element of the multidimensional array is accessed from their index value. But here we use 2 loop.

int arr[2][3];

You can understand this with the help of the program given below.

#include<iostream>
using namespace std;
 int main()
  {
    int i,j,r=1,s=1,x[2][3];              // array variable declaration

    for(i= 0; i<2; i++)
     {
       for(j= 0; j<3; j++)
        {
          cout<<"Enter "<<r++<<" element in x["<<i<<"]["<<j<<"]: ";
          cin>>x[i][j];
        }
     }

  cout<<"Displaying array element: ";
   for(i= 0; i<2; i++)
     {
       for(j= 0; j<3; j++)
        {
          cout<<endl<<s++<<" Element store array in x["<<i<<"]["<<j<<"] is: "<<x[i][j];      // store 5 value at a time
        }
     }

return 0;
 }

OUTPUT

Enter 1 element in x[0][0]: 2
Enter 2 element in x[0][1]: 3
Enter 3 element in x[0][2]: 1
Enter 4 element in x[1][0]: 5
Enter 5 element in x[1][1]: 6
Enter 6 element in x[1][2]: 4

Displaying array element: 
1 Element store array in x[0][0] is: 2
2 Element store array in x[0][1] is: 3
3 Element store array in x[0][2] is: 1
4 Element store array in x[1][0] is: 5
5 Element store array in x[1][1] is: 6
6 Element store array in x[1][2] is: 4

Related Exercise

More about array

Character Array in C++.


Previous – Array in C++
Next- structure in C++


Like it?

Leave a Reply

Your email address will not be published.