Arrays that we have Constructed 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[row_size][column_size]
- Row_size specifies the no. of rows
- column_size specifies the no. of columns.
Example:
int a[4][5]
This is 2-D array of 4 rows and 5 columns. Here, the first element of array is a[0][0] and last element of array is a[3][4] and total number of elements is 4*5=20.
| col0 | col1 | col2 | col3 | col4 |
row0 | a[0][0] | a[0][1] | a[0][2] | a [0][3] | a[0][4] |
row1 | a[1][0] | a[1][1] | a[1][2] | a [1][3] | a[1][4] |
rowr2 | a[2][0] | a[2][1] | a[2][2] | a [2][3] | a[2][4] |
row3 | a[3][0] | a[3][1] | a[3][2] |a [3][3] | a[3][4] |
Initialization:
2-D Array 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}
The values are assigned as follows:
| m[0][0]:1 | | a[0][1]:2 | | a[0][2]:3 |
| m[1][0]:4 | | a[1][1]:5 | | a[1][2]:6 |
| m[2][0]:7 | | a[2][1]:8 | | a[2][2]:9 |
| m[3][0]:10 | | a[3][1]:11 | | a[3][2]:12 |
Note:
In 2-D Arrays it is optional to specify the first dimension but the second dimension should always be present.
Example:
int m[4][3]={
{1,10},
{2,20,200},
{3},
{4,40,400}
};
Here, the first dimension is taken 4 since there are 4 rows in the initialization list. A 2-D Array is known as matrix.
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];
- Reading Values in a
- for(i=0;i<4;i++)
- for(j=0;j<5;j++)
- scanf(“%d”, &a[i][j]);
- Displaying values of a
- for(i=0;i<4;i++)
- for(j=0;j<5;j++)
- printf(“%d”, a[i][j]);