Wednesday, February 9, 2011

Working with Multi Dimensional Arrays

Today I have been practicing multi-dimensional arrays. Its probably one of my favorite concepts in programming with C. What I like about it is the fact that there can be many dimensions of arrays depending on what you want to do with them. For example for character arrays if I wanted a one dimensional array it would hold a bunch of characters making one string. If I wanted more strings within an array I'd need a two dimensional array. A way I've thought about it is this.

char columns[50];                 /* a  one dimensional array holding characters of that first dimension */
char rows[60][50]                /* a  two dimensional array holding rows of one dimensional arrays or columns
char pages[900][60][50]      /* a three dimensional array that looks a lot like a book now.
char books[1000][900][60][50]  /* a four dimensional array that could hold a bunch of books or a library */
char libraries[1000][1000][900][60][50]  /* a five dimensional array that could hold a bunch of libraries */
char towns[50000][1000][1000][900][60][50]  /* a 6 dimensional for towns and all their libraries */
char states[70][50000][1000][1000][900][60][50]  /* a 7 dimensional array to hold states/provinces */
char states[300][70][50000][1000][1000][900][60][50] /* an 8th dimension for countries */
/* to go further we'd need to travel faster than light which is not possible right now */
/* to go even further we'd need to travel between galaxies */
/* if more than one universe exists than this could be possible */

I made a small program that only shows 3 dimensions as it would require more time to go deeper into them.

#include <stdio.h>

void display(char str[][3][50]);

int main(){



 char pages[][3][50] = {{"First row of page 1",
                         "Second row of page 1",
                         "Third row of page 1"},
                        {"First row of page 2",
                         "Second row of page 2",
                         "Third row of page 2"}};
 display(pages);

 return 0;

}

void display(char str[][3][50]){

  int i;
  int j;
  int k;

  printf("\n");

  for (i = 0; i < 2; i++){               /* pages */
    for (k = 0; k < 3; k++){             /* rows */
       for (j = 0; str[i][k][j]; j++){   /* cols */
          printf("%c",str[i][k][j]);
       }
       j = 0;
       printf("\n");
    }
    k = 0;
    printf("\n");
  }
}




I won't go into detail explaining what it does, but put it here for people who are interested to try out. The more dimensions you go into the more for loops it takes to access the data. There may be a better way to access the data, but haven't learned it yet.

Thats all I have to say for now about multi-dimensional arrays.

No comments:

Post a Comment