Showing posts with label Two Dimensional Array. Show all posts
Showing posts with label Two Dimensional Array. Show all posts

Tuesday, 27 March 2012

Two Dimensional Array




Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row & the other the column. It is referred as two dimensional array.
The declaration of two dimension arrays is as follows:

data_type  array_name[row_size][column_size];

Here, data_type is any valid c data type. array_name specifies name of an array. First value in subscript is represent number of rows and second value represent number of column.

Ex   int x[3][5];

Here x is declared as a matrix having 3 rows( numbered from 0 to 2) and 5 columns(numbered 0 through 4). The first element of the matrix is x[0][0] and the last row last column is x[2][4].
         


Column[0]
Column [1]
Column [2]
Column [3]
Column [4]
Row[0]
1
[0][0]
2
[0][1]
3
[0][2]
4
[0][3]
5
[0][4]
Row [1]
11
[1][0]
12
[1][1]
13
[1][2]
14
[1][3]
15
[1][4]
Row [2]
21
[2][0]
22
[2][1]
23
[2][2]
24
[2][3]
25
[2][4]










Ac

Ac

According to above representation of two dimensional array, the  3rd element  of 1st row represented as x[0][2] and here its value is 3


Initialization of two dimensional array

è    Similar to the one-dimensional the two-dimensional arrays are initialized.
Ex, int array[2][3] = {1,2,3,4,5,6};
In the above case elements of the first row are initialized to 1,2,3 & second row elements are initialized to 4,5,6.
                  
1
2
3
4
5
6

è    The initialization can be done row wise also.
Ex, int array[2][3] = {{1,2,3},{4,5,6}};
è    If the initialization has some missing values then they are automatically initialized to 0.
Ex, int array[2][3] = {{3.4},{5}}
In this case the first two elements of the first  row are initialized to 3,4 ,while the first element of the second row is initialized to 5 & rest all elements are initialized to 0.
                            
3
4
0
5
0
0

       Ex,
       void main()
       {
                 int i,j;
                 int mat[3][3];

                 printf(“\n Input \n” );
                 for(i=0;i<3;i++)
                 {
                          for(j=0;j<3;j++)
                          {
                                    printf(“\n enter element [%d][%d] : “,i+1,j+1);
                                    scanf(“%d”,&mat[i][j]);
                          }
                 }
                 printf(“\n output \n” );
for(i=0;i<3;i++)
                 {
                          for(j=0;j<3;j++)
                          {
                                    printf(“%d”,mat[i][j]);
                          }
                          printf(“\n”);
                 }
      
       }

Posted By : Ruchita Pandya