This blog is under construction

Tuesday, 7 January 2014

Multidimensional arrays in C

Multidimensional array is also known as array of arrays.  C allows user to write arrays with one or more dimensions.  An array with more than one dimension is a multi-dimensional array.  Two dimensional array is a simplest form of multidimensional array.  Below is the general form of multidimensional array.

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

Consider the following example
int arr[2][2][2] = {   { {1, 1}, {1, 1} },
                                  { {1, 1}, {1, 1} }
                              };
 
The above statement shows the declaration and initialization of multidimensional array(3d array).  Total number of elements in an array can be obtained by multiplying the size value in each dimension.

int arr[2][2][2];
2 X 2 X 2 = 8 elements in the array arr

And multidimensional array can be accessed using its array indices.
arr[0][0][1] = 2;

The above statement assigns 2 to arr[0][0][1].  Then the resultant value of the array arr would be the following.

     { {1, 2}, {1, 1} },
     { {1, 1}, {1, 1} }
};


Example C program using multidimensional arrays:
#include <stdio.h> 
  int main() {
        int i, j, k, three_dim[2][2][2] = {  // array initialization
                                {{1, 1}, {1, 1}},
                                {{1, 1}, {1, 1}}
                              };

        // printing elements of the array
        printf("Elements of the array three_dim:\n");
        for (i = 0; i < 2; i++)
                for (j = 0; j < 2; j++)
                        for (k = 0; k < 2; k++)
                                printf("three_dim[%d][%d][%d]: %d\n",
                                        i, j, k, three_dim[i][j][k]);

        printf("\nAssign 2 to three_dim[0][0][1]\n");
        three_dim[0][0][1] = 2;  // modifying an array element

        // printing elements of the array
        printf("\nElements of the array after modification:\n");
        for (i = 0; i < 2; i++)
                for (j = 0; j < 2; j++)
                        for (k = 0; k < 2; k++)
                                printf("three_dim[%d][%d][%d]: %d\n",
                                                i, j, k, three_dim[i][j][k]);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Elements of the array three_dim:
  three_dim[0][0][0]: 1
  three_dim[0][0][1]: 1
  three_dim[0][1][0]: 1
  three_dim[0][1][1]: 1
  three_dim[1][0][0]: 1
  three_dim[1][0][1]: 1
  three_dim[1][1][0]: 1
  three_dim[1][1][1]: 1

  Assign 2 to three_dim[0][0][1]

  Elements of the array after modification:
  three_dim[0][0][0]: 1
  three_dim[0][0][1]: 2
  three_dim[0][1][0]: 1
  three_dim[0][1][1]: 1
  three_dim[1][0][0]: 1
  three_dim[1][0][1]: 1
  three_dim[1][1][0]: 1
  three_dim[1][1][1]: 1



No comments:

Post a Comment