Website For Developers

Multidimensional array in C++



2-D Array in C++


Syntax of 2-D array declaration

//datatype identifier [length][length];
int array2d [2][3];


Syntax of 2-D array initialization

//datatype identifier [length] = {{ELEMENTS} , {ELEMENTS}};

int array2d [2][3] = {{2, 4, 6} , {1, 3, 5}};
array2d[0][0] = 2
array2d[0][1] = 4
array2d[0][2] = 6
array2d[1][0] = 1
array2d[1][1] = 3
array2d[1][2] = 5
Indexes 0 1 2
0 2 4 6
1 1 3 5

Example of Multidimensional array in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int array[3][4]= {{1, 2, 3, 4} , {9, 8, 7, 0} , {3, 3, 3, 3}};
  for (int i=0; i<3; i++) {
    for (int j=0; j<4; j++) {
    cout<<array[i][j]<<" ";
    }
    cout<<endl;
  }
  getch();
  return 0;
}

Output

1 2 3 4
9 8 7 0
3 3 3 3



Example of 2-D array in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int max, min;
  int a[2][3];
  cout<<"Please enter the values"<<endl;
  for(int i=0; i<2; i++) {
    for(int j=0; j<3; j++) {
    cin>>a[i][j];
    }
  }

  for(int i=0; i<2; i++) {
    for(int j=0; j<3; j++) {
      if(a[i][j]>max)
        max = a[i][j];
      if(a[i][j]<min)
        min = a[i][j];
    }
  }
  cout<<"Maximum value is: "<<max<<endl<<"Minimun value is: "<<min<<endl;
  getch();
  return 0;
  }

Output

Please enter the values
2
235
43
64
765
54
Maximum value is: 765
Minimum value is: 1