Tuesday 12 February 2013

Two Dimensional Arrays in C Programming Language



In the last cycle, we learnt the concept of one dimensional arrays in C language. C also supports multidimensinal arrays and the simplest form of the multidimensional array is the two - dimensional array. A two-d array is in essence an array of single dimensional arrays. The general form of declaration fo the two-d array would be

type arrayname[x][y];

Note that each dimension of the two-d array has been placed in a separate set of brackets. Two-d arrays are stored in a row-column matrix, in which the first index indicates the row and the second indicates the column. To access a specific element, both the indices or subscripts have to be specified.


Initialising Two Dimensional Arrays

The rules for initialising a two-d array are the same as for a one dimensional array. Initialisation at the time of declaration must be done outside the function or must be declared static within the function. Consider the following example:

int squares[10][2]={
{1,1}
{2,4}
{3,9}
{4,16}
{5,25}
}

The row subscript may be left blank for a more flexible declaration. The compilar will automatically calculate the row dimension based on the number of values initialised. The inner sets of curly braces are optional. However, in the case of initialising the array with only some and not all values, these curly braces assume a lot of importance.
For Example:

int sales[3][4]={
{143,274},
{336,543,876},
{442,421,765,996},
};

only two elements of the first row, three in the second row and four in the third row are initialised.

0 comments:

Post a Comment

Powered by Blogger.