2D Array / Array of Array / Matrix

Syntax :

datatype variable_name[][];

//here first braces indicates Number of Rows
// and second indicates Number of Column.
  • In 2D Array, the elements are 1D Array.
  • In 1D Array, the elements are integer or character.
  • For example, int a[6] = int a[2][3]  this both are same in size and it is 24 bytes and we can store total six integer or character variables in it.
  • One Advantage of using 2D Array is, we can easily maintain the array.

Example :

#include<stdio.h>
main()
{
        int a[2][3] = {10,20,30,40,50,60},i,j;
        int row = sizeof(a)/sizeof(a[0]);  //find a size of number of row
        int column = sizeof(a[0])/sizeof(a[0][0]);  //find a size of number of column
        for(i=0 ; i < row ; i++)
        {
           for(j=0; j < column ; j++)
           {
              printf("%d ",a[i][j]);     //printing elements of 2D Array one by one
              printf("\n");
           }
        }
}
     

Output : 10
          20 
          30
          40 
          50
          60
  • Here is a[2][3], a[2] is optional means row Because already it is a 2D array. So, we can write b[][3]
  • but vice versa is not possible it will give an error. i.e. a[2][];

How to Scan a 2D Array?

for(i=0 ; i < row ; i++)
{
    for(j=0; j < column ; j++)
    {
          scanf("%d",&a[i][j]);      
    }
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: