HitBrother

Two-dimensional array (Matrix) In C

Two-dimensional array is popularly known as tables or matrix and can be easily visualised as having rows and columns. Matrix can also be thought of as arrays of arrays.
To create a two-dimensional array, specifying both dimensions i.e. rows and columns in square brackets.

For e.g. the following declaration creates a matrix of 4 rows and 5 columns.
int mat[4][5];
or
#define MAXROW 3
#define MAXCOL 4
int mat[MAXROW][MAXCOL];

Array are stored in row order, thus the expression mat[0] represents the first row of 5 values,mat[1]represents second row, mat[2]represents third row, and so on. Similarity the expression mat[0][0] refers to the upper left value in the matrix, mat[2][3] represents the fourth value in third row.
Matrix initializes:-
1. int mat[4][3];
2. int mat[4][3]={{10,20,30,40},{50,60,70,80},{90,100,110,120}};
3. int mat[4][3]={10,20,30,40,50,60,70,80,90,100,110,120};
4. Static int mat[4][3];

Note1:- int mat[ ][ ] is invalid because dimensions are not specified.
Note2:- int mat[ ][ ]={1,2,3,4,5,6} is invalid because it is not possible to decide the row & column of the matrix.
Note3:- int mat[ ][3]={1,2,3,4,5,6} is valid
Note4:- int mat[2][ ]={1,2,3,4,5,6} is invalid as column is compulsory in matrix declaration.

Advertisement

Coding Of  2-d Array

#include<stdio.h>
int main()
{
   /* 2D array declaration*/
   int disp[3][5];

   /*Counter variables for the loop*/
   int i, j;

   for(i=0; i<=2; i++)
   {
       for(j=0;j<=4;j++)
       {
          printf("Enter value for disp[%d][%d]:", i, j);
          scanf("%d", &disp[i][j]);
       }
    }
    return 0;
}

 

Advertisement