Ads block

Banner 728x90px

Multi-Dimensional Array


Multidimensional array are defined in the same manner as one dimensional arrays, except that a seperate pair of square brackets are required for each subscript (index).

Two-dimensional arrays are as a grid. A two dimensional array will require two pairs of square brackets and a three dimensional array will require three pairs of brackets and so on.


The general format of the multidimensional array is:

storage_class data_type arrayname [expression_1][expression_2][expresssion_3];

Example

int value [20][30];  // 2-dimensional array
float coordinate [10][10][10];  // 3-dimensional array
char name [15][30];

The first line of the example defines the value as a integer type array having 20 rows, 30 columns with total of 600 elements. The second one is a three dimensional floating point array whose maximum size is 1000 elements.

In two dimensional array the upper left corner of any grid would be [0][0]. The element to its right would be [0][1], so on. Here is a little illustration to help.

[0][0][0][1][0][2]
[1][0][1][1][1][2]
[2][0][2][1][2][2]


Initialization

Similar to one dimensional array, multidimensional arrays can also be initialized.

// initialization of multidimensional array
int a[2][2] = {1,2,3,4};

where a is a two dimensional array of integer numbers whose maximum size is 4 and its assignment would be


              a[0][0] = 1;
              a[0][1] = 2;
              a[1][0] = 3;
              a[1][1] = 4;


A two-dimensional array is a grid, and a three dimensional array is as a cube. The above declaration would give you 27 integers (3 x 3 x 3).
Just like other arrays, it can be initialize like this


int a[][][]={  1, 2, 3,
               4, 5, 6,
               7, 8, 9,
               10, 11, 12,
               13, 14, 15,
               16, 17, 18,
               19, 20, 21,
               22, 23, 24,
               25, 26, 27,           }

Accessing Elements Of Two-Dimensional Array

Elements of two-dimensional arrrays can be accessed as follows:

a[0][0] = 10;    // assigns 10 to element at first row and first column
a[0][1] = 5;    // assigns 5 to element at first row and second column
a[2][3] = 32;    // assigns 32 to element at second row and third column


// Program to print the elements of two dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
   int a[3][3], i, j;
   clrscr();
   printf("Enter the array elements");
   for (i=0; i<=2; i++)
    {
      for (i=0; j<=2; j++)
      {
        scanf("%d", &a[i][j]);
      }
    }
   printf("The elements of the array are");
   for (i=0; i<=2; i++)
   {
      for (j=0; j<=2; j++)
      {
        printf("%d", a[i][j]);
      }
      printf("\n");
   }
   getch();
}


Enter the array elements
     4   6   8
     7   2   1
     1   1   3
The elements of the array are
     4   6   8
     7   2   1
     1   1   3