blogger Indonesia

Follow judhyns blog

TWO-DIMENSIONAL ARRAY

Introduction

You can define two- or multi-dimensional arrays. It is taken as an array of an array. Logically, the two-dimensional array 3 X 2 is taken as

 3     1  5     2  8     7 

Here there are three arrays, i.e. one array in each row. The values are stored as

3   1  5   2    8  7 

This style is called row measure form. Each row array is represented as a[0], which consists of elements 3 and 1. a[1] consists of 5 2 and a[2] consists of 8 7. Each element of a[0] is accessed as a [0] [0] and a[0] [1], thus the value of a[0][0] and a[0][1] is 1.

Program

 #include  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.

Points to Remember

  1. You can define a multi-dimensional array in C.

  2. You have to provide multiple subscripts for accessing array elements.

  3. You can access array elements by using a pointer.

No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |