Two Dimensional Arrays

PropellerAds

Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.

Declaration:
The syntax is same as for 1-D array but here 2 subscripts are used.

Syntax: data_type array_name[rowsize][columnsize];

Rowsize specifies the no.of rows

Columnsize specifies the no.of columns.

Example:
int a[4][5];

Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.

Example:
int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};

Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and
the inner loop indicates the columns.

Example:
int a[4][5];
a) Reading values in a
for(i=0;i<4;i++)
 for(j=0;j<5;j++)
 scanf(“%d”,&a[i][j]);

b) Displaying values of a
for(i=0;i<4;i++)
 for(j=0;j<5;j++)
 printf(“%d”,a[i][j]);

Multidimensional Array
More than 2-dimensional arrays are treated as multidimensional arrays.
Example:
int a[2][3][4];

Here a represents two 2-dimensional arrays and each of these 2-d arrays contains 3 rows and 4
columns.

Initialization:

int a[2][4][3]={
{
{1,2,3},
{4,5},
{6,7,8},
{9}
},
{
{10,11},
{12,13,14},
{15,16},
{17,18,19}
}
}

Try Now – Programming In C MCQs