Friday, March 18, 2011

Program for Three-Dimensional Array with Explanation

program

#include <stdio.h>
main()
{
    int a[2][3][4];   \\ A
    int b[3][4];      \\ B
    int c[4];         \\ C
    int cnt=0;
    for(int i=0;i<2;i++)
        for(int j=0;j<3;j++)
               for(int k=0;k<4;k++)
               {
                      a[i][j][k] = cnt;
                      cnt;
               }
}
void print_onedim(int a[])   \\ D
{
    for(int i=0;i<4;i++)
        printf("%d ",a[i]);
}
void print_twodim(int a[][4])           \\ E
{
    for(int j=0;j<3;j++)
        print_onedim(a[j]);
    printf("\n");
}
void print_threedim(int a[][3][4])      \\ F
{
    printf("Each two dimension matrix\n");
    for(int j=0;j<2;j++)
        print_twodim(a[j]);;
}

Explanation

  1. The three-dimensional array consists of two arrays of the size 3 × 4. Each is referred to as a[0] a[1]. Thus a[0] consists of 12 elements and a[1] also consists of 12 elements.
  2. Each two-dimensional array is taken as three arrays of the size 4.
  3. The function print_onedim prints a single-dimensional array.
  4. The function print_twodim prints a two-dimensional array and it calls the function for printing a single-dimensional value.
  5. The function print_threedim prints a three-dimensional array and calls the function for printing a three-dimensional value.
  6. Dimension two, which is closer to the array name, is called the outermost dimension, and dimension four, which is far from the array name declaration, is called the innermost dimension.
  7. When you pass an array to the function, you have to specify the inner dimension. For example, to print two_dim you have to specify the inner dimension, i.e. 4, and for printthree_dim you have to pass 3 and 4 as inner dimensions.
  8. When you pass a single-dimension array, you need not pass a dimension because the function knows what the best address of the array is.
  9. In a case of a two-dimensional array, we have to pass the inner dimension because only then does the function know the base address of each array. For example, if the declaration is
    int a[3][4]
    
    it is considered as three arrays of the size 4. So the base address of a[0] is a itself. The base address of a[1] is a+8 because the first row has 4 elements of size 2 bytes each; thus we can get the base address of a[1]. Similarly, the base address of a[2] is a+16. Thus, to calculate the base address, you should know the inner dimension, 4

No comments:

Post a Comment