Multi-dimensional Array In C

The C language also support multi-dimensional array. The general form of multi-dimensional array declaration will look like this :
datatype array_name[size1][size2]....[sizeN];
For example the below statement create a three dimensional int array :
int myarr[3][3][2];
Two-Dimensional Array :

The simplest form of a multidimensional array is the two-dimensional array. In simple words a two dimensional array is an array of one-dimensional array. A two-dimensional array can be considered as a table with rows and columns. The syntax for declaring two dimensional array is :
int myarr[X][Y];
Where X denotes the number of rows and Y denotes the number of columns. For example :
int a[3][3];
The above statement is create a table of 3 rows and 3 columns.


Initialization of two-dimensional Array :

Initialization of array at the time of declaration :
int a[3][3] = {
               {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
              };

And we can also initialized the array elements on by one.
int[0][0] = 1;<br/>
int[0][1] = 2;<br/>
int[0][2] = 3;<br/>
int[1][0] = 4;<br/>
int[1][1] = 5;<br/>
int[1][2] = 6;<br/>
int[2][0] = 7;<br/>
int[2][1] = 8;<br/>
int[2][2] =  9;
Accessing Array Values :

An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array.
a[2][1];
The above statement will give the 8th value of the two dimensional array above declared. Now lets see the example of two dimensional array.

Example :
#include <stdio.h>

int main() {

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

  // print values
  int x,y;
  for(x=0; x<3; x++) {
    for(y=0; y<3; y++) {
      printf("%d\n", a[x][y]);
    }
  }
    
  return 0;
}
Output :

1
2
3
4
5
6
7
8
9


Next Topic :