Two dimensional arrays - Syntax and Examples with Explanation | Coding classpoint

Two dimensional arrays



Two dimensional array is known as matrix. The array declaration in both the array i.e.in single dimensional array single subscript is used and in two dimensional array two subscripts are is used.

Its syntax is

Data-type array name[row][column]; 
Or we can say 2-d array is a collection of 1-D array placed one below the other. 
Total no. of elements in 2-D array is calculated as row*column

Example 

int a[2][3]; 
Total no of elements=row*column is 2*3 =6 
It means the matrix consist of 2 rows and 3 columns

For example 
20 2 7 
8 3 15

Positions of 2-D array elements in an array are as below 
00 01 02 
10 11 12


Accessing 2-d array /processing 2-d arrays

For processing 2-d array, we use two nested for loops. The outer for loop corresponds to the row and the inner for loop corresponds to the column. 

For example 
int a[4][5];

for reading value:

for(i=0;i<4;i++) 
for(j=0;j<5;j++) 
scanf(“%d”,&a[i][j]); 
}

For displaying value

for(i=0;i<4;i++) 
for(j=0;j<5;j++) 
printf(“%d”,a[i][j]); 

Initialization of 2-d array: 

2-D array can be initialized in a way similar to that of 1-D array. 

for example:- int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22}; 

These values are assigned to the elements row wise, so the values of elements after this initialization are 

Mat[0][0]=11,    Mat[1][0]=14,    Mat[2][0]=17    Mat[3][0]=20 

Mat[0][1]=12,    Mat[1][1]=15,    Mat[2][1]=18    Mat[3][1]=21 

Mat[0][2]=13,    Mat[1][2]=16,    Mat[2][2]=19    Mat[3][2]=22 

While initializing we can group the elements row wise using inner braces. 

for example:- int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}}; 

And while initializing , it is necessary to mention the 2nd dimension where 1st dimension is optional. 

int mat[][3]; 

int mat[2][3];

int mat[][];  int mat[2][]; - Invalid

If we initialize an array as 

 int mat[4][3]={{11},{12,13},{14,15,16},{17}};

Then the compiler will assume its all rest value as 0,which are not defined.

Mat[0][0]=11,   Mat[1][0]=12,     Mat[2][0]=14,    Mat[3][0]=17 

Mat[0][1]=0,     Mat[1][1]=13,     Mat[2][1]=15     Mat[3][1]=0 

Mat[0][2]=0,     Mat[1][2]=0,       Mat[2][2]=16,    Mat[3][2]=0

In memory map whether it is 1-D or 2-D, elements are stored in one contiguous manner. 

We can also give the size of the 2-D array by using symbolic constant

Such as 

 #define ROW 2;

#define COLUMN 3;

 int mat[ROW][COLUMN];

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.