C 2D Arrays


The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arrays or list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.


Declaration of 2D Array

Syntax

data_type array_name[size1][size2];  

Example

int 2darr[4][3];  

Initialization of 2D Array

Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

Example

int a[3][4] = {  
 {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
 {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
 {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional.

Example

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array.

Syntax

int val = a[2][3];

Example of 2D array

#include <stdio.h>
 
int main ()
{
   /* an array with 5 rows and 2 columns*/
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
   int i, j;
 
   /* output each array element's value */
   for ( i = 0; i < 5; i++ )
   {
      for ( j = 0; j < 2; j++ )
      {
         printf("2darray[%d][%d] = %d\n", i,j, a[i][j] );
      }
   }
   return 0;
}
Output
2darray[0][0]: 0
2darray[0][1]: 0
2darray[1][0]: 1
2darray[1][1]: 2
2darray[2][0]: 2
2darray[2][1]: 4
2darray[3][0]: 3
2darray[3][1]: 6
2darray[4][0]: 4
2darray[4][1]: 8

Share this article on