Tuesday 3 January 2012

Multi Dimensional Array


Syntax:type array_name[d1][d2][d3][d4]………[dn];Where dn is the size of last dimension.
Example:int table[5][5][20];float arr[5][6][5][6][5];In our example array “table” is a 3D (A 3D array is an array of arrays of arrays.) array which can hold 500 integer type elements. And array “arr” is a 5D array which can hold 4500 floating-point elements. Can see the power of array over variable? When it comes to hold multiple values in a C programming, we need to declare several variables (for example to store 150 integers) but in case of array, a single array can hold thousands of values (depending on compiler, array type etc).
Note: To make this multidimensional array example simple I will discuss 3D array for the sake of simplicity. Once you grab the logic how 3D array works then you can handle 4D array or any multidimensional array easily.How to Declaration and Initialization 3D ArrayBefore we move to serious programming let's have a look of 3D array. A 3D array can be assumed as an array of arrays of arrays, it is array (collection) of 2D arrays and as you know 2D array itself is array of 1D array. It sounds a bit confusing but don't worry as you will lead your learning on multidimensional array, you will grasp all logic and concept.
We can initialize a 3D array at the compile time as we initialize any other variable or array, by default an un-initialized 3D array contains garbage value. Let’s see a complete example on how we can work with a 3D array.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=  
        {
            {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
            },
            {
            {21, 22, 23},
            {24, 25, 26},
            {27, 28, 29}
            },
            {
            {31, 32, 33},
            {34, 35, 36},
            {37, 38, 39}
            },
        };
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        printf("%d\t",arr[i][j][k]);
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}

No comments:

Post a Comment

host gator coupon