Page 51 - DCAP407_DATA_STRUCTURE
P. 51
Data Structure
M k1, k2, k3…….kn or M[k1, k2, ……….kn]
A two-dimensional array marks[2][3] is given in the example.
marks[0][0]
15.5
marks[0][1]
20.5
marks[0][2]
25.5
marks[1][0]
30.5
marks[1][1]
35.5
marks[1][2]
40.5
The first element is given by marks[0][0] which contains 15.5, the second
element marks[0][1] contains 20.5, and so on.
Initialization of Multidimensional Arrays
Like the one dimension arrays, two-dimensional arrays are also initialized by declaring a list of initial
values enclosed in braces.
int table[2][3]={0,0,0,1,1,1};
The table array initializes the elements of first row to 0 and the second row to
1. The initialization is done row by row. The above statement can be
equivalently written as:
int table[2][3]={{0,0,0},{1,1,1}}
Three or four-dimensional arrays are more complicated. They can also be initialized by declaring a list
of initial values enclosed in braces.
int table[3][3][3]={1,2,3,4,5 6,7,8,…………….27 };
This will create an array named table containing 27 integers. We can access any
element of this array by using 3 indices.
The method to access table[1][1][1], is as shown below:
The values for array - table[3][3][3] are as follows:
{1, 2, 3}
{4, 5, 6}
{7, 8, 9}
{10, 11, 12}
{13, 14, 15}
{16, 17, 18}
{19, 20, 21}
{22, 23, 24}
{25, 26, 27}
The values in the array can be accessed using three for loops. The loop contains
three variables i, j, and k respectively. This is as shown below:
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
44 LOVELY PROFESSIONAL UNIVERSITY