Learn Multidimensional Arrays In C

In the previous tutorial on arrays we have seen how to declare, initialize and access the array elements. But we have only seen one dimensional arrays. In c language, we can create and use multidimensional arrays also.

Syntax to Declare Multidimensional Array


data-type array_name[size1][size2][size3]..[sizeN];


The most basic multidimensional array is two dimensional array.
For Example:

int arr[3][3];

We can initialize this as follows:

int arr[3][3]={

		{1,2,3},
		{4,5,6},
		{7,8,9},

			};

Above is same as

int arr[3][3]={1,2,3,4,5,6,7,8,9};

If you declare an array as arr[m][n], it can hold maximum m x n elements.

Here is character array to store names of 5 characters each.

int arr[5][3]={

		{S,a,m,a,r},
		{A,a,m,i,r},
		{A,m,b,e,r},

			};

For two dimensional array, you can consider the elements are stored like table of rows and columns. Index starts from 0 for both rows and columns and increments by 1. In above example the first dimension represent the rows and second represent the columns. So there are 5 rows and 3 columns. Hence the maximun index row can have is 5-1 i.e. 4 and for column it is 3-1 i.e. 2.

We can access the array elements by using indices as given below:

int arr[2][2],i,j,r=2,c=2; // r,c are used for number of rows and column

arr[0][0]=1;// indicates the first element at (0,0) will be assigned 1

arr[0][1]=2;

arr[1][0]=3;

arr[1][1]=4;

for(i=0i<r;i++)
	for(j=0;j<c;j++)
		printf(" %d ",arr[i][j]);


/* Output of above code:


1 2 3 4


*/

Consider the following example:

int arr[3][3][4];

What do you think of above array declaration? We can imagine it as 4 tables of 3x3.

Examples For Practice

  1. C program to add two matrices
  2. C program to check identity matrix
  3. C program to accept n strings and display the largest
  4. C program to find the transpose of a matrix

Comments