Two- Dimensional Arrays

 

 

 

 

TWO DIMENSIONAL ARRAYS

Two dimensional arrays are used to arrange data in tabular form. In these arrays we have rows and columns. It is basically a two dimensional matrix with specific number of rows and columns.

For Example: -
int a[4][3];
 

This represents a two-dimensional array of integer type with 4 rows and 3 columns.
Each element is referred by its row and column number.
 

For Example:-

a[0][0],a[1][0],a[3][0],a[0][1],a[3][2] etc.
 

Where ,

a[i][j] represents elements of array.

  • Two dimensional arrays find a wide range of applications in maintaining records.

 

For Example:-

•    Marks obtained by different students in different subjects.
•    No of different items sold by number of salesgirl.
 

SYNTAX

Data type  array_name[row_size][column_size];
 

For Example:- a[0][0],a[1][0],...a[3][0],a[0][1],........a[i-1][j-1]

Where ‘i’ represents row size and ‘j’ represents column size.
 

ARRAY DECLARATION

•    int  marks[][3]={
           {2 1,6}    
           {3,5,9}
         };

  • Note:-It is necessary to specify size of column in array declaration but row can be left empty.

•    Char array[3][2];

  • Values in the elements of array can be assigned at the run time or by assignment operator in program itself as we did in case of One- Dimensional array.

Example: - To add two matrix of dimensions 2X3, with one matrix having defined values and one given at run time.
 

#include<stdio.h>
#include<conio.h>

int main()
{
int i=0,j=0,k=0;
int a[2][3]={2,3,6,1,0,8};
int b[2][3]={0}, sum[2][3]={0};
clrscr();
printf(" Enter the elements of matrix 'b'\n");
for(i=0;i<2;i++)
    for(j=0;j<3;j++)

        {
        printf(" Element No. %d-",k+1);
        scanf("%d",&b[i][j]);
        k++;
        }

for(i=0;i<2;i++)
    for(j=0;j<3;j++)
    {
     sum[i][j]=(a[i][j]+b[i][j]);
    }

for(i=0;i<2;i++)
    for(j=0;j<3;j++)

        {
        printf("%d, ",sum[i][j]);
        }

getch();
}

 

EXPLANANTION
 

This example finds the sum of two 2X3 matrix, in which matrix ‘a’ has values fed into the source code itself and values in ‘b’ is taken from standard input device during run time.
Finaly sum is found out and printed on the standard output device, in my case it is monitor.

OUTPUT

Enter the elements of matrix ‘b’
Element No. 1-3
Element No. 2-2
Element No. 3-5
Element No. 4-6
Element No. 5-7
Element No. 6-9

Sum of matrix ‘a’ and ‘b’: -
5, 5, 11, 7, 7, 17