Array Classifications

 Arrays are classified into the following types.

       One-Dimensional Arrays
       Two-Dimensional Arrays
       Multidimensional Arrays


One Dimensional Arrays:
The collection of elements of similar data type stored in contiguous memory location under one variable name with single subscript.

     int num[4];


 Data Item num[0] num[1] num[2] num[3]
 Address 1000 1004 1008 1012


Two Dimensional Array:
A set of data items stored under a common name with two subscripts and it can be thought of as a rectangular display of elements with rows and columns as shown below.

     int num[4][4];

column1 column2column3column4
 Row1num[0][0]num[0][1]num[0][2]num[0][3]
 Row2num[1][0]num[1][1]num[1][2]num[1][3]
 Row3num[2][0]num[2][1]num[2][2]num[2][3]
 Row4num[3][0]num[3][1]num[3][2]num[3][3]


Multidimensional Array:
Two dimensional array is the simplest form of multidimensional array.  A set of data elements stored under a single variable name with more than 1 subscripts is called multidimensional array.  Below is an example for three dimensional array which is also a multidimensional array.

     int num[3][3][3] = {
     {
       {1, 1, 1},
       {1, 1, 1},
       {1, 1, 1}
     },

     {
       {1, 1, 1},
       {1, 1, 1},
       {1, 1, 1}
     },

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



Example C program on one dimensional and two dimensional array

#include <stdio.h> 
  int main() {
        int num[5], two_dim[3][3], i, j;

        // assigning values to one dimensional array elements
        for (i = 0; i < 5; i++) {
                num[i] = i;
        }

        // assigning value to two dimensional array elements
        for (i = 0; i < 3; i++)
                for (j=0; j < 3; j++)
                        two_dim[i][j] = i + j;

        // printing values of one dimensional array
        for (i = 0; i < 5; i++)
                printf("%d\t", num[i]);
        printf("\n\n");

        // printing the values in two dimensional array
        for (i = 0; i < 3; i++) {
                for (j = 0; j < 3; j++) {
                   printf("%d ", two_dim[i][j]);
                }
                printf("\n");
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  0    1    2    3    4   

  0  1  2
  1  2  3
  2  3  4





Example C program using three-dimensional array

#include <stdio.h> 
  int main() {
        int num[3][3][3], i, j, k;
        for (i=0; i < 3; i++){
           for (j=0; j < 3; j++) {
              for(k=0; k < 3; k++) {
                num[i][j][k] = k;
                printf("%d  ", num[i][j][k]);
              }
              printf("\n");
           }
           printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  0  1  2
  0  1  2
  0  1  2

  0  1  2
  0  1  2
  0  1  2

  0  1  2
  0  1  2
  0  1  2

No comments:

Post a Comment