Friday, March 18, 2011

Program for Two-Dimensional Arrays with Explanation

Program

#include <stdio.h>
void printarr(int a[][]);
void printdetail(int a[][]);
void print_usingptr(int a[][]);
main()
{
    int a[3][2];      \\ A
    for(int i = 0;i<3;i++)
        for(int j=0;j<2 ;j++)
        {
               {
                     a[i]=i;
               }
        }
    printdetail(a);
}
void printarr(int a[][])
{
    for(int i = 0;i<3;i++)
        for(int j=0;j<2;j++)
        {
               {
                      printf("value in array %d\n",a[i][j]);
               }
        }
}
void printdetail(int a[][])
{
    for(int i = 0;i<3;i++)
        for(int j=0;j<2;j++)
        {
               {
                      printf(
                      "value in array %d and address is %8u\n",
                      a[i][j],&a[i][j]);
               }
        }
}
void print_usingptr(int a[][])
{
    int *b;   \\ B
    b=a;                \\ C
    for(int i = 0;i<6;i++)   \\ D
    {
        printf("value in array %d and address is %16lu\n",*b,b);
        b++; // increase by 2 bytes \\ E
    }
}

Explanation

  1. Statement A declares a two-dimensional array of the size 3 × 2.
  2. The size of the array is 3 × 2, or 6.
  3. Each array element is accessed using two subscripts.
  4. You can use two for loops to access the array. Since i is used for accessing a row, the outer loop prints elements row-wise, that is, for each value of i, all the column values are printed.
  5. You can access the element of the array by using a pointer.
  6. Statement B assigns the base address of the array to the pointer.
  7. The for loop at statement C increments the pointer and prints the value that is pointed to by the pointer. The number of iterations done by the for loop, 6, is equal to the array.
  8. Using the output, you can verify that C is using row measure form for storing a two-dimensional array.

No comments:

Post a Comment