C++ Multidimensional Arrays

A C++ multidimensional array has more dimensions identified by the number of subscripts. In this article, you will learn about a two-dimensional array in detail.

Two-dimensional Array

A two-dimensional array has rows and columns. The horizontal arrangement of elements within a two-dimensional array is row and vertical arrangement is a column.

For example,

A[2][4] means that this two-dimensional element is from 3rd row and 5th column. The row or column index starts at 0.

Two-dimensional Array Declaration

To declare a 2d array like any variable does the following.

<data_type><array_name>[m][n];

The ism no of rows and equalsn no of columns.

Example #1

int account [3][4];

float boxes[2][3];

The example shows that the array account has 3 rows and 4 columns indicated by subscripts.

Two-dimensional Array Initialisation

Initialising two-dimensional array means assigning initial values. There are two ways to do that.

Consider following examples,

int matrix [3][3];
matrix [3][3] = {5,6,8,1,4,7,9,2,0};

First, note that the total number of values are equal to 3 × 3 – rows X columns.

int bins[2][2];

bins[2][2] = {{23, 45},{78, 43}};

The first internal brace is the first row and never changes. Similarly, the second brace is the second row.

Also, you can initialise 2a d array dynamically. See the example program below.

/* Program to demonstrate 
two-dimensional array
*/

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int sq_matrix[3][3];
int i,j;

//Reading values for matrix 

cout << "Enter matrix values";

for(i =0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin >> sq_matrix [i][j];
}
}
//print the array

for(i =0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout << sq_matrix [i][j] << " ";
}
cout << endl;
}

system("PAUSE");
return EXIT_SUCCESS;
}

Output

Enter matrix values4
8
9
0
8
4
2
9
7
4 8 9
0 8 4
2 9 7

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag