C++ Multi dimensional Array

  • Home
  • C++
  • C++ Multi dimensional Array

Two Dimensional Array


Use Two subscript to specify size of a two dimensional array.

Syntax


<Type> Array_name[R][C]


Here, Type refers data type.
Arraay_name is the name of the array
[ ] brackets declare size of array. R specifies the maximum number of rows.
C specifies the maximum number of columns

Program to assign and display two dimensional array.



#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int a[2][2];
    a[0][0]=20;
    a[0][1]=40;
    a[1][0]=30;
    a[1][1]=10;
    cout<<"\na[0][0] = "<<a[0][0];
    cout<<"\na[0][1] = "<<a[0][1];
    cout<<"\na[1][0] = "<<a[1][0];
    cout<<"\na[1][1] = "<<a[1][1];
    getch();
}


Output

a[0][0]=20
a[0][1]=40
a[1][0]=30
a[1][1]=10


Program to initialize a two dimensional array.



#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int i,j;
    int a[3][2]={3,2
         5,6,
         8,9
    };
    int b[3][3]={
      {6,9,8},
      {2,6,8},
      {4,9,3}
    };
   cout<<"\n Matrix a =";
   for(i=0;i<3;i++)
   {
     cout<<"\n";
     for(j=0;j<2;j++)
     {
         cout<<"\t"<<a[i][j];
     }
   }
   cout<<"\n Matrix b =";
   for(i=0;i<3;i++)
   {
      cout<<"\n";
      for(j=0;j<3;j++)
      {
          cout<<"\t"<<b[i][j];
      }
   }
    getch();
}


Output

Matrix a=
3     4
5     6
8     9
Matrix b=
6      9      8
2      6      8
4      9      3

Back To Top