Wednesday, November 2, 2011

Two Dimensional Arrays in C programming language

So far we have explored arrays with only one dimension. It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix. Here is a sample program that stores roll number and marks obtained by a student side by side in a matrix.

main( )
{
      int  stud[4][2] ;
      int  i, j ;

      for ( i = 0 ; i <= 3 ; i++ )
 {
            printf ( "\n Enter roll no. and marks" ) ;
            scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
 }

      for ( i = 0 ; i <= 3 ; i++ )
            printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

There are two parts to the program—in the first part through a for loop we read in the values of roll no. and marks, whereas, in second part through another for loop we print out these values. Look at the scanf( ) statement used in the first for loop:

scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;

In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for every student. The second subscript tells which of the two columns are we talking about—the zeroth column which contains the roll no. or the first column which contains the marks. Remember the counting of rows and columns begin with zero. The complete array arrangement is shown below.


Thus, 1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above arrangement highlights the fact that a two- dimensional array is nothing but a collection of a number of one- dimensional arrays placed one below the other. In our sample program the array elements have been stored rowwise and accessed rowwise. However, you can access the array elements columnwise as well. Traditionally, the array elements are being stored and accessed rowwise; therefore we would also stick to the same strategy.

1 comment: