HTML

html content help to improve the coding

Wednesday, 28 March 2012

MULTIDIMENSIONAL ARRAY IN C++


For each dimension of your array, you will need another for loop. For instance, if I have a 2-D array:

int myMatrix[ROWS][COLS];

Then I would fill it by saying something like:

1
2
3
4
5
for (int i = 0; i < ROWS; i++) {
   for (int j = 0; i < COLS; j++) {
      myMatrix[i][j] = i + j; // or whatever.
   }
}

Well I guess the next dimension would be a 3d array. So:
int 3darray[5][5][5];
This would give you an array that is 5 ints tall, 5ints wide, 5 ints thick.
To add a values to all the parts you would need:
1
2
3
4
5
6
7
8
9
10
for(int i = 0;i < 5; i++)
{
       for(int u = 0; u < 5; u++)
       {
                for (int p = 0;p < 5; p++
                {
                           3darray[i][u][p] = (i + u + p);
                }
       } 
}


Displaying would be more complicated - depending on the way you want to display, I could think of a way but it wouldn't be very good.

I don't know about more then 3d arrays though.


And here's four-d arrays, for good measure.

1
2
3
4
5
6
7
8
9
10
11
12
13

void main(){
   int four_d_array[4][15][23][8];
   for(int i = 0; i < 4; i++){
      for(int j = 0; j < 15; j++){
         for(int k = 0; k < 23; k++){
            for(int l = 0; l < 8; l++){
               four_d_array[i][j][k][l] = whateverValue();
            }
         }
      }
   }
}


for five-d and beyond, You should be able to look at what we've given you and see the pattern emerging. Just add some more square brackets and for loops.

No comments:

Post a Comment