2d array in C | Initialisation and Program

Written by

Pooja Rao

Multidimensional Arrays

C language allows multidimensional arrays.

Syntax of a multidimensional array declaration  is:

data_type array_name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional array of integers:

int multidimension[5][10][4];

The simplest form of multidimensional array is the two-dimensional(2d) array.

A two-dimensional array is a list of one-dimensional arrays.

Two Dimensional Arrays in C and Programs

  • An array of arrays is known as a 2D array.
  • The two dimensional (2D) array in s also known as a matrix. A matrix can be represented as a table of rows and columns

Syntax:

data_type array_name [ r ][c ];

Where data_type can be any valid C data type and array_name will be a valid C identifier. A two-dimensional array can be considered as a table which will have r number of rows and c number of columns.
2D arrays are widely used to solve mathematical problems, image processing, and translation, board games, databases etc.

Accessing array elements:

  • Consider your menu card you might have 3 categories i.e starters, main course, and dessert. Under each category, you might have multiple items which belong to it.
  • Here, the food category becomes your rows i.e. ‘r’ and items listed under each will be the elements in the columns ‘c’. This leads to 2D array creation, consider A.

 

c = 0 c = 1 c = 2
(Starters) r = 0 A[0, 0] A[0, 1] A[0, 2]
(Main course) r = 1 A[1, 0] A[1, 1] A[1,2]
(Desserts) r = 2 A[2, 0] A[2, 1] A[2, 2]

 

Every element is accessed by row and column subscript or index. such as A[0,0] / A[1,0] etc. Thus it is A[r,c]. where r is rows and c is columns.

Initialization of Array elements:

2D Arrays can be initialized in several ways.

First is simply to specify the size of array with array elements.

Example: Here we have initialized an array having 2 rows and 3 columns.

int a[2][3] = {  

  {1, 3, 1},  /* initializers for row indexed by 0 */

  {4, 5, 6}   /* initializers for row indexed by 1 */

 };

The nested {} braces are optional, however, it improves the readability as it indicated the end of a particular row.

 

int a[2][3] = {  1, 3, 1, 4, 5, 6 };

The above declaration is also equivalent.

int a[2][2] = {1, 2, 3 ,4 }  /* Valid declaration*/
int a[][2] = {1, 2, 3 ,4 }   /* Valid declaration*/
int abc[][] = {1, 2, 3 ,4 }    /* Invalid declaration – you must specify second dimension that is column size*/
int abc[2][] = {1, 2, 3 ,4 } /* Invalid declaration – you must specify second dimension that is column size*/

We shall see the reason to specify column size through the next few sections.

2d array in C | Initialisation and Program